#archived-code-general

1 messages ยท Page 413 of 1

unkempt swallow
#

ive never seen something like this in my life

#

also the solution im gonna use is that github repo and this code

#

no idea if its what i wanted, but the values look good enough i guess

polar marten
#

it will use code analysis

#

pay for plus

#

i mean the $20/mo

vestal arch
#

why not use stuff that's specialized specifically for that kind of stuff

chilly surge
#

It doesn't matter what the mean is or whatever, from that curve they draw, for example f(7) is about 5x as f(350), so what they want is for a 7 kg fish to be 5x as likely to appear than a 350 kg fish. They want to be able to randomize according to this curve, and they want to be able to adjust this curve.
I've already explained the general algorithm to achieve the "randomize according to any curve" part. If doing the integral is a bit too hard math wise, then well you just have to pick curves that you can do, or use a library that handles all the integrating for you.

vestal arch
#

instead of, yknow, a hallucinogenic LLM

polar marten
#

๐Ÿฅบ

unkempt swallow
polar marten
#

don't worry about it

chilly surge
#

How is it wrong?

vestal arch
#

you wanna explain why?

chilly surge
#

I can do an example calculation right now to demonstrate how it works.

unkempt swallow
#

i mean what Burrito wrote is exactly what i want (function wise)

#

any example would be great, im down to test it out, the solution i have now is not ideal since it still has many high numbers

polar marten
#

a way to think about this is, that if you want the "Average" fish to be about 20kg, choose a scale of 1/5, because that is 20% of the way between 20kg and your "max" of 100kg
so you want weights between 1 and 100. you will discard and reroll above 100kg.
so something like randomexponential(scale=1/5) * 100 + 1. if it's greater than 100, reroll.
here is the plot, which is basically what you want

#

does that make sense @unkempt swallow ?

latent latch
#

If you did computer algs or probability you'd run into it

chilly surge
#

They want adjustable curve, not just one specific curve.

polar marten
#

๐Ÿฅบ

#

focus on what i am saying

#

i know a lot about this

unkempt swallow
unkempt swallow
polar marten
#

the important thing is that when you want something like "really rare fish weights", but for gameplay purposes you want to discard fish above 100kg, i mean, go for it

unkempt swallow
#

im so confused rn CRY

polar marten
#

i already wrote what you need to do

unkempt swallow
polar marten
#

randomexponential(scale=1/5) * 100 + 1. if it's greater than 100, reroll.

chilly surge
vestal arch
polar marten
#

i know how to translate what you want into statistiquese. but. if you just asked chatgpt to author this for you from scratch, it probably would succeed

polar marten
#

it just isn't correct

#

anything you want to do something random. you know, there's what you want to achieve with gameplay. i already told you the best way to do it is to create a deck, and replace the cards after you draw.
but if you don't want to do that, the thing i am describing is basically the same process

unkempt swallow
#

from what i read i think you both are saying the same thing but you are saying their solution is wrong

unkempt swallow
#

RandomExponential rnndn = new RandomExponential(0,0.025f);

#

i thought this would be correct but it isnt

polar marten
#

i think you should maybe take a breather

#

or ask chatgpt to do it for you. it will give you a correct answer. buy plus

unkempt swallow
#

so if i want 100 to be the max i use 0.01?

polar marten
#

no.

vestal arch
#

why are you here to sell chatgpt lmao ๐Ÿ˜‚

polar marten
#

๐Ÿฅบ

hexed pecan
#

It's so absurd

polar marten
vestal arch
#

@unkempt swallow you wanna have a try with an animation curve?

polar marten
#

you can't turn an animation curve into a histogram...

#

it doesn't work the way you think it does

#

you would just be doing the process of making the deck

#

and drawing from it

vestal arch
polar marten
#

you drew a histogram. yo ujust don't know that you drew a histogram

vestal arch
#

yeah

#

well no

#

not really

#

actually no it wouldn't be a histogram

polar marten
#

look at the title of the chart i got out of chatgpt. i asked for a histogram. an animation curve evaluated at time t, where teh aniomation curve is a histogram, is telling you the frequency of that value

#

see. that's because you're all confused. he was indeed drawing a histogram. that is a PDF...

#

you can't just draw a PDF and sample from it.

craggy veldt
vestal arch
polar marten
#

you would have to do another step. which is exactly the same thing as what chatgpt did, which is generating a bajillion samples. and then you're back at square one

#

๐Ÿฅบ

#

listen anything is possible!

#

you are overthinking this

polar marten
#

i can't edit a screenshot for you

vestal arch
polar marten
#

@unkempt swallow everything you need is directly in front of you

unkempt swallow
#

i cant see it

#

๐Ÿ‘จโ€๐Ÿฆฏ

polar marten
#

can you copy and paste your code

#

into backticks @unkempt swallow

#

just do that for me

unkempt swallow
#
            RandomExponential rnndn = new RandomExponential(1,0.01f);
            float thenumber = rnndn.Get();
            testlist.Add(thenumber.ConvertTo<int>());
#

this is my current code

vestal arch
#

!code

tawny elkBOT
north hatch
#

Does anyone know how to make for exemple i pick up a key and then lets say when i turn around a jumpscare plays whats it called?

latent latch
#

well, you're triggering something by picking up a key, but the jumpscare to happen you'd probably check if it's currently in the viewing frustrum after spawning it

#

@north hatch

polar marten
#

you are in a good place and very aspiring

#

it will help you with a lot of instruction

unkempt swallow
#

i am beyond poor bro

polar marten
#

well i think the free version also works well

#

certainly well enough

north hatch
polar marten
#

this is a simple enough problem for o1 mini

unkempt swallow
#

why is there a while loop

polar marten
unkempt swallow
#

why do i even have to redraw / discard

polar marten
#

this stuff will get easier

unkempt swallow
#

thats like wasted computer power no

polar marten
#

because that's what it would be in real life

#

hmm. well the last thing i'll say is the general approach to these problems is

#

try to do it how you would od it if you were implementing a board game

vestal arch
polar marten
#

in cardware. then you can translate your cardware board game rules into code. it will be a lot easier

#

that's why i said, make a deck of a 100 fish. then shuffle it. then look at the top card. that's your fish. then shuffle it and look at it again for the next fish

latent latch
polar marten
#

does that make sense?

#

@unkempt swallow so think with board games first.

unkempt swallow
#

using this i get only 100, 100 times

vestal arch
polar marten
#

in the discord window

#

i've told you a bajillion times how to do this

#

i've even shown you a chart that gives you what you want

unkempt swallow
#

using the code you posted i get 100 times the result 100

polar marten
#

i know.

#

i think i have exhuasted my energy on this, i'm sorry.

unkempt swallow
#

@chilly surge please ๐Ÿ™

polar marten
#

i didn't want to program into the discord chat window

#

you still are responsible for writing your own code

thin aurora
#

Make a thread

#

Jesus

polar marten
#

i think you are best served by asking chatgpt

craggy veldt
#

wtf

latent latch
#

didnt we get here because of chatgpt

polar marten
vestal arch
#

yeah ok the animation curve works fine as far as i can tell

polar marten
#

and ultimately wants a snippet of code that "just" does what he asked for

latent latch
#

animation curve is bff

chilly surge
# unkempt swallow please write the example

Here's an example math:

Let's say you want to randomize a fish's weight in the range 100 kg to 200 kg, with a customizable curve. Let's say you mess around and end up with a curve like y = 0.2 * x + 100 and you feel like that's the one, now here's how you would do the randomization part:

  • Integrate y = 0.2 * x + 100, you get a result of 0.1 * x^2 + 100 * x + C.
  • Plug in x = 100 (your lower bound), you get 11000 + C.
  • Plug in x = 200 (your upper bound), you get 24000 + C.
  • That's it, in your code you can use Random.Range(11000, 24000) to get a random number.
    Let's say the randomizer gives you back 20000, now you need to calculate what kg of fish it corresponds to:
  • You solve the equation: 0.1 * x^2 + 100 * x = 20000, which gives you x = 170.8, so player fished up a 170.8 kg fish.

This math uses y = 0.2 * x + 100, but the same calculation works for any curve you want, so you can adjust the curve to however you like and plug in the same math to randomize fish weight according to it.

polar marten
#

๐Ÿฅบ

#

the animation curve by itself doesn't solve th eproblem. you still end up sampling it...

#

there are

#

a million ways to do this

#

i'm not saying one is right or one is wrong.

vestal arch
polar marten
vestal arch
#

im not saying it's better

polar marten
#

lol

#

i know i know

#

i think the user got what he needed.

latent latch
#

imagine having to go on desmos and visualizing your curve

vestal arch
#

it's more achievable for kinami

latent latch
#

no one has time for that

polar marten
#

yeah... we'll see about that

vestal arch
#

because you can just draw something like this and not do any math

polar marten
#

yeah...

#

if you are just evaluating that curve with random t 0 to 1

#

it won't be correct

#

is that what you are doing?

vestal arch
#

yes

#

why wouldn't it be correct

#

it's not a pdf

polar marten
#

what is it exactly lol

hexed pecan
vestal arch
#

it might be a cdf, idk ๐Ÿ˜›

polar marten
#

lol exactly

#

you basically drew a random curve!

vestal arch
#

but you don't need to know any math to use it

vestal arch
polar marten
#

it's not hard to turn the exponential dist pdf / histogram into a curve that works the way where you draw it and sample it, but they're not the same!

#

you need to know math to do that transformation!

vestal arch
#

do you need to do that transformation though?

polar marten
#

well...

vestal arch
#

exponential curve might not work in the general case anyways lol

polar marten
#

you know, go ahead and try to make that histogram lol

#

i know

vestal arch
#

why should i?

polar marten
#

it's okay. we've spent enough cycles on it

#

because the histogram is how you measure the behavior

thin aurora
vestal arch
#

sure

polar marten
#

it's how you know if you did it right

#

@chilly surge you can draw a curve that is a histogram. but the way to use it is to create a "deck" of "1,000" cards, each with a value written on it from animationcurve(random.random). then shuffle the deck, then draw a card, then discard thd eck.

#

does that make sense?

#

it's not enough to just call animationcurve(random.random)

chilly surge
#

Sorry but I don't think you even read what I've written, it has nothing to do with animation curve.

polar marten
#

if you want to draw a curve that is the inverse of a pdf, you can, but that is hard

hexed pecan
#

It's a video game, I don't think anyone notices if the random distribution uses a perfect math formula or if it's sampled from an animation curve

polar marten
#

before you take any of the other steps

#

so what if i draw a line between 100kg and 200kg. what does it mean?

#

succinctly

#

before these steps with integrations or whatever

#

which, btw, is just doing the histogram, and sampling from it. this is valid! i sort of know what the curve means. there are lots of valid approaches. but at least say succinctly, what does x and f(x) mean

chilly surge
polar marten
polar marten
#

that's a pdf then, yes?

#

you actually want the inverse of the pdf, not the integral

polar marten
#

inverse meaning, f_inv ( f ( x ) ) = x

#

the integral wouldn't make sense

vestal arch
#

does exactly what i intended it to do

chilly surge
#

๐Ÿคฆ

polar marten
#

well we can only reason about stuff that makes sense with real math no?

chilly surge
#

I'm done with this conversation, OP got what they asked for.

polar marten
#

there's a reason that's what people use to communicate things

vestal arch
#

this isn't a math server lol

polar marten
#

it is now!

#

you better start believing in math if you wanna make games!

vestal arch
#

here we get stuff done, unlike mathematicians

polar marten
#

lol

#

i appreciate that this was a stylized comment. but c'mon guys. if you want to elevate above the chatbot, you should adhere to like, real educational stuff

#

as much as i love being admonished for telling a "juster" kind of user who "just" wants an answer for using a chatbot. well... it's fun to talk about what's really going on

#

if you want to draw a pdf using an animation curve, that is, the user needs to draw a curve in the eidtor that looks what he drew earlier, you would need to compute the inverse of it

#

that's just the approach. you wouldn't take the integral

chilly surge
#

If you believe my math is wrong, you are welcomed to sample according to the math I've given above and see for yourself that the resulting histogram does match the curve given.

polar marten
#

i just punch into google "how to sample from pdf" and the answer is "inverse of pdf"

#

which isn't generalizable for something like gaussian, which you can see for yourself in all the implementations

thin aurora
#

Maybe you guys should request a math-and-procrastination channel

#

Instead of here

polar marten
#

i can't believe people are coming out as anti-math!

#

seriously everyone will write much better games if you learn this stuff

#

i've been talking for ages about modeling it with decks. that's really good for designing games too!

vagrant blade
#

This is beyond Unity related now, move on.

chilly surge
vagrant blade
#

If you want to continue debating this, you can make a thread.

vestal arch
#

anyways, @unkempt swallow, if you're still interested in using an animation curve;
with a serialized AnimationCurve, you can edit the curve directly. it would basically be a mapping between the Random.value and the output value.
for example, #archived-code-general message with this example, the min value is 5, there's a high chance to get values around 30 (the flat area), there's a 75% chance to get an output under 50 (consider the value at t=0.75)
histogram for that demo curve: #archived-code-general message

when drawing the curve, make sure to edit the start and end points to be at exactly 0 and 1, and set the min/max that way as well (right click the points > edit point)
right click the points to set the tangents to weighted to freely control the curve, and you can add more points as needed
to sample it, you would do curve.Evaluate(Random.value)

viscid plaza
#

Movement inside car

unkempt swallow
# vestal arch anyways, <@210457762021244928>, if you're still interested in using an animation...

i understand everything besides the last thing you said, i think it contradicts what you said before?

when drawing the curve, make sure to edit the start and end points to be at exactly 0 and 1, and set the min/max that way as well (right click the points > edit point)
right click the points to set the tangents to weighted to freely control the curve, and you can add more points as needed
to sample it, you would do curve.Evaluate(Random.value) 

can you rephrase this

vestal arch
#

which part

#

and ive said a lot of things, what exactly contradicts what?

unkempt swallow
#

i think the animation curve does nothing at all, because you still use Random.Value, so lets say i get 0.8 which on the curve would be at .8? what is the point of the curve, i dont understand

#

0 to 1

#

ohh time is on the left

heady iris
#

the input is on the X axis

#

the output is on the Y axis

unkempt swallow
#

i see yeah

vestal arch
#

animation curves are normally for, well, animations, where the x axis is time, and the y axis is what to do

heady iris
#

I use animation curves for this kind of thing pretty often

vestal arch
#

so if you get 0.8, you would sample at that "time", and get ~0.3

unkempt swallow
#

ye

#

this is great and i think i will use this often, exactly what i wanted
what my friend helped me with is this now

    public float decay = 1.5f;
   
    public float GetRandomRarity()
    {
        
       float randomValue = Random.Range(0f,1f);

        float rarity = -Mathf.Log(1 - randomValue) / decay;

       return rarity * 10;
      
    }

which gets me basically values up to infitiy lmao with the option to adjust

#

ill stick with the anim curve tho, i like the numbers more ThumbsUp

#

in 100 rolls, only 5 were above 0.5, perfect

#

ty ty

stuck harness
#

If I am going to use steamworks inventory system thing later for my cosmetic stuff, is it smart to use like scripteble objects and save them in some way until I get into steam works? or should I make it in anther way for a more smooth transition?

polar marten
kind nymph
#

ok so this code was ORIGINALLY made to apply to transform.rotation.z and not rigidbody2.rotation so i switched it to rigidbody to comply with physics instead of bypassing it by changing from Quaternion.Euler() to rigidbody2.MoveRotation(). It kinda works but once angle reaches 180 it snaps to -180 and vice versa. If this isn't the right way to do this then I'm not surprised but unfortunately I don't know the right way (why does rotation have to be so complicated)

private void AimMouse()
{
    Vector3 mousePos = Input.mousePosition;

    Vector3 objectPos = Camera.main.WorldToScreenPoint(transform.position);
    mousePos.x = mousePos.x - objectPos.x;
    mousePos.y = mousePos.y - objectPos.y;

    float angle = Mathf.Atan2(mousePos.y, mousePos.x) * Mathf.Rad2Deg;
    Debug.Log(angle.ToString());
    rigidbody.MoveRotation(Mathf.Lerp(rb.rotation, angle, 0.05f));
}
pulsar plinth
#

hello guys
sooooo I've been trying to find the solution for this problem, but haven't been able to
I'm creating this one pixel art 640x360 game and I used to be making it in Gamemaker 2 since it was the engine I used to use but the project's code became complex really quickly and now I've needed to transition into Unity if I didn't want the game's specs to be ridiculously high. In GM2, sprites can be rendered through a single function which does the job, however it seems like the only way to render sprites in Unity is by using the sprite renderer component but this doesn't allow an asset to render more than 1 sprite at a time which would be very useful to create many things.
TL DR: I would like to know if there's a function which renders sprites, thus allowing more than a single sprite to be drawn with a single asset instead of having to create an asset with the sprite rendenr component for each sprite

#

by the way, despite being a complex project its camera always only displays a 640x360 slice of the game so it shouldn't be problematic to use a single game object for each sprite since I'll use a rendering deactivations for offscreen regardless, it just isn't ideal

steady bobcat
#

Look into particle systems too

pulsar plinth
#

I see

#

I'll make sure to

#

thanks btw

kind nymph
# pulsar plinth hello guys sooooo I've been trying to find the solution for this problem, but ha...

if you mean can you render multiple sprites at the same time with one SpriteRenderer then refer to what the guy above me said, but if you just mean rendering different sprites with one SpriteRenderer then that's definitely possible, one method is to the SpriteRenderer's sprite directly at runtime by referencing another sprite

public class Example : MonoBehaviour
{
    public Sprite spriteA; // The first sprite
    public Sprite spriteB; // The second sprite
    private bool spriteToggle; // Whether to use the first or second sprite
    private SpriteRenderer sprRend; // The GameObject's SpriteRenderer Component

    void Start()
    {
        sprRend = gameObject.GetComponent<SpriteRenderer>(); // Get the reference to the GameObject's SpriteRenderer Component
    }

    if (spriteToggle) // If spriteToggle is true
    {
        sprRend.sprite = spriteB; // Set the SpriteRenderer's sprite to spriteB
    } else // Otherwise
    {
        sprRend.sprite = spriteA; // Set the SpriteRenderer's sprite to spriteA
    }
    
    /*
      Toggles the sprites. You would need to call this elsewhere at runtime by getting a reference to this GameObject's Script's Component, and then doing Example.ToggleSprite(). Alternatively you can Invoke the function with a callback from a button or similar
    */
    public void ToggleSprite()
    {
        spriteToggle = !spriteToggle;
    }
}

funnily enough im also porting a GM2 game to unity so if u have any other questions i (might) be able to help you

pulsar plinth
#

I did find out a function which does exactly that
Graphics.DrawTexture()

west drum
#

Can somebody help me with this code i cant find the solution. I want it to do a dash with an animation of dash. The dash was pretty ez but after the dash it keeps itself in that animation and is in the last frame until i change the state so if i move it works again but else it stays in dashstate

steady bobcat
pulsar plinth
pulsar plinth
kind nymph
steady bobcat
#

its going to be different per game. If in built solutions dont work and profiling confirms the problem is too many game objects/ poor batching then its worth looking at code only mesh drawing.

polar marten
polar marten
#

absolutely do not use Graphics.DrawTexture at this stage

#

for a 2d game

#

that you have barely started writing

#

even for thousands of sprites

pulsar plinth
#

but what are the cons of DrawTexture, exactly?

polar marten
#

your computer is drawing thousands of sprites right now right in front of you (the text glyphs). trust me. you should use the sprite renderer

polar marten
steady bobcat
#

unless you are doing vampire survivors level of sprites then you probably dont need it

polar marten
steady bobcat
#

oh i know. i got to speak to one of the devs last halloween at their party ๐Ÿ˜„

polar marten
#

you just don't need it period

#

lol

pulsar plinth
steady bobcat
#

I have a squishy garlic ๐Ÿง„

polar marten
kind nymph
# polar marten what are you trying to do? is this a top down adventure game with a rigidbody ba...

it's top down but it's not point and click, it's a 2D space game.

it's not exactly physics based it just uses the linearVelocity attribute of Rigidbody2D so I can have acceleration and deceleration without any of the complicated transform manipulation business.

previously AimMouse() used to work with transform because it was bypassing physics but now I'm changing it so it doesn't do that and it has resulted in unexpected behaviour (as many abrupt conversions do)

polar marten
#

it is always going to be slower than spriterenderer

steady bobcat
#

vampire survivors has a port of the old engines physics engine (from the old js engine) as they needed it to be exactly the same
but due to perf issues they stagger some things on different frames.

polar marten
pulsar plinth
polar marten
#

this will give you physics and a nice framework for experimenting with controls if that's your goal

pulsar plinth
#

hmm, is vampire survivors really done using sprite renderer?

polar marten
#

yes

#

110%

#

why wouldn't it? why assume that something right in front of you would be slow

kind nymph
heady iris
#

unity can reason about all of your sprite renderers at once

pulsar plinth
heady iris
#

unity can't reason about a bunch of DrawTexture calls

polar marten
#

it might feel that way

#

and i get it. it matters, something that feels true is true

kind nymph
polar marten
#

but you don't actually know

#

come at this with an open mind

#

keep chugging along

#

you can go ahead and use graphics.drawtexture. nothing bad will happen

#

if that makes you want to work on your game.

pulsar plinth
#

though, as I've also said, the game will not be cluttered with sprites in each frame like Vampire Survivors
so I'll sprite renderers instead

polar marten
#

if you are looking for validation, go for it

pulsar plinth
#

(unless I notice optimization problems, then I'll have to get deeper into meshes and etc.)

polar marten
#

choose whatever will make you excited to work on your game

polar marten
#

that's how i do it in all my games

#

so that it's non kinematic but still feels very snappy

pulsar plinth
polar marten
#

computing the right amount of angular velocity such that the rigidbody very stiffly rotates towards the mouse and abruptly stops rotating when it is facing the mouse is exactly as hard as implementing a framework for joints

#

@kind nymph does that make sense?

kind nymph
polar marten
#

okay cool

kind nymph
#

of course I would need to tweak the settings so it doesnt bounce too much

#

but thank you for the insight ๐Ÿ‘

polar marten
pulsar plinth
#

I looked it up but it costs
plus I don't think my game is that complex either

hollow anvil
#

does anyone know if i can single out and debug a script ran by an object that other objects are sharing that script? For an example if have a bunch of enemies running their own enemy script. How can i debug one particular enemy and its script ?

steady bobcat
#

if logs, you can add a context object as an arg to Debug.Log: Debug.Log("foo", this);

hollow anvil
#

i see ! i didnt think of using conditional break points to do that, though is there a faster way to single out the game object for debug ? The bug im trying to pin down happens semi often and i would prefer not to having to manually change the gameObject name everytime

steady bobcat
#

well unless you can create a condition that identifies this object then its not going be easy
Sometimes its wise to add a check in code manually somewhere to detect a bug so you can log it and even pause the debugger.

hollow anvil
#

yeah the bug im having doesnt really cause run time error but just some logic error that is causing animation issues for my objects. I guess ill just stick to conditional break points. I worked with Unreal for a little bit and it was much simpler whenver I wanted to take a look at a specific object to debug. Im too spoiled from that lol.

#

thanks for the help!

heady iris
#

or, if you haven't figured out how to use conditional breakpoints yet, you can just throw in

if (someCondition) {
  Debug.Log("Put the breakpoint here.");
}
steady bobcat
#

dunno how you did it in unreal but its not a unity specific issue.
it is sometimes better to just add an if for the breakpoint condition as conditional breakpoints can reduce framerate

stuck harness
simple void
#

This isn't a very technical question more so design choice. Say I have a lot of instances of some entities(e.g. animals) roaming around all using the same material&shader that displays vertex colors. I want when they are damaged to display a different color, like red. Should I quickly switch out the materials? Create new material properties? Have a buffer for all instances and also detail which entity instance a vertex is in its vertex information passed to the shader so I can just change the buffer's information?

heady iris
#

That depends a bit on which render pipeline you're using

#

Material property blocks would be my go-to in the built-in RP

#

that lets you override specific properties on each renderer

#

In the scriptable render pipelines (URP and HDRP), the SRP Batcher only works if you aren't using material property blocks

#

you're intended to just create a material instance for each renderer

#

(by accessing renderer.material)

#

If you're rendering a huge number of non-skinned meshes, you could do instanced rendering. In that case, you'd want to use material property blocks again

simple void
#

Thanks for the input, Iโ€™m using URP for skinned meshes(theyโ€™re animated), I want the render pipeline to avoid creating a draw call for each instance, in terms of performance I think itโ€™d be much more preferred if I just inject the instance index through as a vertex property to lookup in a buffer. But that is a pain to setup obviously.

heady iris
#

You can't avoid the draw calls, AFAIK -- you're drawing many different meshes (after skinning)

#

but the SRP Batcher can give you better performance e

simple void
#

I see, I guess quickly switching the material isnโ€™t that bad, if I just have two shared materials for each state. Just wondering whether there was a more correct way

heady iris
#

It should be roughly the same to have:

  • one material for "normal" and one material for "hurt"
  • one material for every single renderer
#

I'd guess the former is better, but the SRP Batcher can handle both

simple void
#

Thatโ€™s fair I suppose the difference is pretty negligible, this whole conversation is pretty nitpicky

edgy ether
#

dunno if this should be in general or advanced coding but here's what i wanna do.

i want to make an editor script that accesses the selected imported textures from the project and allow me to assign secondary textures to them via script.

but i dont know if it's possible to access and set the secondary texture in the project.

is it possible to get and modify this information in script instead of manually clicking one at a time?

i was planning to make a script to set them all in bulk based on my naming convention

cosmic rain
heady iris
#

It's a sprite thing

#

It lets you associate multiple textures with a sprite

#

I also completely forgot about that and had to google it :p

edgy ether
#

yeah, sometimes stuff like specular maps, emissions and etc

heady iris
#

A sprite is just a reference to a texture + where to sample from it

edgy ether
#

yeah, but basically what i want to do is get code to access the ability to add/change the secondary texture so i dont gotta manually add it in for hundreds of textures

heady iris
#

I see a secondaryTextures property in here

#

(I copy-pasted a sprite sub-asset so that I could look at its actual serialized data directly

edgy ether
#

i see, so it probably would b e about getting the file and guid and type to add it

cosmic rain
heady iris
#

Ah, there you go

#

Now, if you're trying to modify the secondary textures for sprites produced by an importer, that's a different story

#

I'm not really sure what you'd need to do there

#

maybe an asset postprocessor..?

edgy ether
#

hmm, well i guess i have to look into any possible access to the texture importer scripts..

steady bobcat
#

getting an importer for an asset is often the best way to modify it

heady iris
#

Would you do that in a postprocessor?

#

I'm still pretty uncertain about this stuff myself

steady bobcat
#

Last time i did this i just had a menu item to go over many sprite sheets to change some settings on their importer

heady iris
#

how do you get at the importer?

steady bobcat
heady iris
#

ooh, okay

#

that makes sense

#

changing importer settings in a postprocessor wouldn't make sense

steady bobcat
#

an example from something i did a while ago:

TextureImporter texImporter = (TextureImporter)AssetImporter.GetAtPath(assetPath);
if (texImporter != null)
{
    EditorUtility.SetDirty(AssetDatabase.LoadAssetAtPath<Texture2D>(assetPath));
    TextureImporterSettings texsettings = new TextureImporterSettings();
    texImporter.ReadTextureSettings(texsettings);

    //9 is the custom alignment mode
    if (texsettings.spriteAlignment != 9)
    {
        EditorUtility.SetDirty(texImporter);
        texsettings.spriteAlignment = 9;
        texsettings.spritePivot = newPivot;
        texsettings.ApplyTextureType(TextureImporterType.Sprite);
        texImporter.SetTextureSettings(texsettings);
        texImporter.SaveAndReimport();
    }
}
#

i had issues with shit not saving hence the weird dirty ๐Ÿ˜†

edgy ether
#

this looks interesting, thanks. i'll mess with this another time to see if i can get the result im looking for

pearl burrow
#

hello guys. I've made up a level manager/quest system and all the quests are stored in a list so when i finish the x quest i just go to the x+1. all the quests are scriptable objects (structure in the image). In my json savedata i just save the index value corresponding to the element in the list so i can retrieve easly at which quest i am when i start the game. So all good the "main quest" is done. But i also want to have the possibility to have more quests going on (so sidequests). What you suggest to save in the json for other quests going on (can be multiple ofc). A list of the indexes of a list filled with the side quests? Seems an easy answer but i cant find a solution i like!

#

if i save all the possible sidequests in a list i could easly access them and save the index of all the sidequests going on. but i dont know why it sounds wacky and there is a better way

wicked scroll
#

saving indices is very delicate because if you update your game, they might drift, and it could break people's saves (which maybe is fine! up to you)

you could auto-generate some kind of UUID for each quest and use those to reference each quest uniquely. In practice, I recommend giving them unique string names because it will make your life easier keeping track of everything.

pearl burrow
#

do you mean unique string names that i write. so i load all the quests from the resource folder, use a dictionary of strings and retrieve the quest?

wicked scroll
#

yep

pearl burrow
#

sounds good indeed

#

so i can also attach the quest to where i need in the scene instead of numbers

wicked scroll
#

I would recommend loading them from some kind of 'active quests' object so that you can have quests included which aren't 'live' yet, but it doesn't matter that much

pearl burrow
#

to access the list

#

tysm

wicked scroll
pearl burrow
#

yes they already are indeed

wicked scroll
#

nice, there ya go

pearl burrow
#

and how would you deal with the rewards then. For now for the main quest i have a big class with switches that gives rewards according to my needs

wicked scroll
#

one advantage to readable string IDs is that for debugging it's nice to be able to do stuff like /grant quest tutorial_combat_1

wicked scroll
pearl burrow
#

wait i show you what i mean

#

which is probably ugly

wicked scroll
#

my eyes are too pure to look upon anything ugly

pearl burrow
#

behold

#

rewards can be of anything

#

i dont really understand how a scriptable object can do that

#

using a prefab with a script that does only that probably?

wicked scroll
#

yeah, and that might be valid as well

#

what I would do is define my rewards as data

#

they can't really be anything

pearl burrow
#

yeah sure

wicked scroll
#

they can be unlocking a skill, or setting an element, or adding an element amount

#

and you can define those in a list of rewards with an enum or something in your SO

pearl burrow
#

so i could put in there some flags to represent which reward is it and with some editor scripting making it pretty

wicked scroll
#

yep, and then somewhere you'd map that enum to the actual code to 'grant' that reward

pearl burrow
#

when i do these things i always think "why do i need some value when it may be not used". thats why sometime i get stuck..

#

for example in my scriptable object i have the float Distance and the list of objectives to complete

#

which represents two way to complete the quest

wicked scroll
#

sometimes you can define things abstractly enough, where it's like 'a type and a value' and then you don't have redundancy

wicked scroll
pearl burrow
#

ahaha yeah good one

#

so i should eat what i have and dont worry for now. there will be time to polish

wicked scroll
#

you can have different 'configuration' objects that you switch between in the editor based on the type of quest selected in the dropdown

#

the thing is, 'configuring your game' does not need to be the same as 'running your game'

pearl burrow
#

yeah man, to making it simplier to program youre making it harder to finish

wicked scroll
#

so if it makes sene to have some ugly extra data in there at design time, but then at runtime you build up some objects from that data which are simpler to work with and only have the pieces you need, that's good

pearl burrow
#

alright thanks again, ill delete this class full of switch lmao

wicked scroll
pearl burrow
#

yeah i always thought of it but never did it

#

cause in my mind "what if i need that, or that! or this!!"

wicked scroll
#

of course, sometimes the rewards are highly contextual and it doesn't make sense to say 'this quest always gives this reward', in which case maybe having some systems which handle reward distribution at a higher level like you have make sense (but it would still be good to use tags and things to organize them instead of a per-quest lookup)

wicked scroll
pearl burrow
#

oh one last question

wicked scroll
#

I've landed on 'write only the code you need, only when you need it, and keep it as easy to delete as possible' ๐Ÿ˜„

#

easiness of deletion is a one of the few good code quality metrics

pearl burrow
#

as you can see in the ugly rewards method im using some managers to update the rewards. those are actually services (im using a service locator). In this case its best to attach prefab for the rewards right? cause i dont know if its a good thing to use it in scriptable objects (if its possible too)

#

sorry i mean, im referencing the managers directly. but i might need to use the service locator

wicked scroll
#

it's not something I'd worry about on a solo project

#

C# is really easy to refactor

#

service locator is probably technically better but I don't expect it will matter, and if it does it's pretty easy to go through and update those

#

folks have differing opinions for sure

pearl burrow
#

yeah ok, ill start from somewhere for now

#

also by going to sleep

#

bb and thanks

flat marsh
#

Hi! I'd love it if someone could give some of my code a review. I'm interested to know if there is a more efficient / better way to approach this problem. Please give all feedback as it will help me become better :D

#

For a bit of context, this is a almost done piece of code that I've written in the past couple of days. It is for a skill tree in unity (by almost done I mean its just missing some of the skill effects, I still need to code those but the framework is done). I've commented the whole thing so hopefully that should help

#

Here is also a screenshot of what it looks like in unity (visual WIP, I don't have art for it yet)

#

Each smaller white square is a skill node, the larger one is purely for visuals and the cancel button explains itself

#

Here is also a screenshot of what the inspector for the script looks like:

#

Skill TXT is just where I assign what visual elements explaining the skill tree I want set active

#

Thanks!

#

(Also I'm sorry if this was too large)

mellow mural
#

You could use switch cases for checking your enums instead of a bunch of if else statements

plucky inlet
#

I am wondering, why you always use FindGameObjectsWithTag instead of handling them in script

plucky inlet
#

Imagine you want to extend your skill level and experiencepoint checks to way bigger numbers. you do not really want to mess around with x amount of if statements to get the correct amount of health, stimlevel or whatever all those values are ๐Ÿ˜„

leaden solstice
flat marsh
# plucky inlet Oh yes, I agree with File_Missing, def. look into switch cases and also try not ...

Thanks! I think I might actually look into databases now that you've suggested it :D. As for not using switch statements..... I didn't want an if statement inside every switch case. I did try to use them originally but you cant have another condition in the same line as the switch statement (at least that is my understanding of it) and I need to check multiple conditions to allow the skill to become active.

flat marsh
prime lintel
#

Hi all, is there a way to properly search for a tag where there is only a single instance of the gameobject with such a tag per scene? But only when the scene is loaded and the old one is unloaded?

private void HandleSceneChange(string sceneName, bool showLoadingScreen)
{
    _InterfaceEventChannelSO.RaiseEventLoadingScreen(showLoadingScreen ? true : false);
    new Task(SceneChangeLoadAsync(sceneName, OnSceneLoaded));
    _InterfaceEventChannelSO.RaiseEventLoadingScreen(false);
}

private void OnSceneLoaded()
{
    CameraManager.Instance.UpdateFollow(GameObject.FindGameObjectWithTag("Player").transform);
}

private IEnumerator SceneChangeLoadAsync(string sceneName, System.Action callback)
{
    AsyncOperation asyncLoadScene = SceneManager.LoadSceneAsync(sceneName);

    while (!asyncLoadScene.isDone)
    {
        yield return null;
        callback();
    }
}

my current problem is that it finds the tag of the player from the previous scene in editor mode and returns null in a dev build

leaden solstice
#

Also should try avoid using singletons

flat marsh
plucky inlet
# flat marsh Thanks! I think I might actually look into databases now that you've suggested i...

Yeh the problem lies within your hardcoded stuff. You need to think of it in a more generic way. So a skill tree is a list of skills in a hierarchical order for example. So you could have skills referencing child skills or whatever fits your needs. And then loop check your enums to get the right values back for all your stuff you have in there. So bascially your if loop hardcoded would become your hierarchy in inspector for testing and later in whatever dataformat you want (json preferably or just a simple SO yada yada)

leaden solstice
# flat marsh How come?

Because your code is hardcoded and impossible to add another character with own skill tree and experience etc

flat marsh
leaden solstice
#

Is that even compile or is that Task your own something

prime lintel
plucky inlet
leaden solstice
plucky inlet
#

lol, singleton hater cathei? ๐Ÿ˜„

hexed pecan
prime lintel
# leaden solstice Why

i initially just got into unity at the time and coming from aspnet i didnt really do much coroutine work so I had no idea what i was doing tbh

#

but the code is sacred rn and on the backburner for cleanup

plucky inlet
#

but thats also not your question, right.

leaden solstice
#

There are libraries that supports it and you don't have to do "singleton pattern" shit

hexed pecan
#

This is preference.

plucky inlet
#

objectivity left the room, I guess ๐Ÿ˜‰

leaden solstice
#

If you call bad code a "preference"

plucky inlet
#

Oh boy, we got it. you hate singletons.

leaden solstice
#

And you love it because you don't know how to properly avoid it? ๐Ÿค”

prime lintel
plucky inlet
hexed pecan
leaden solstice
plucky inlet
leaden solstice
#

Or "we want to let player control different character mid-game!"

plucky inlet
#

ohhhh, thats the reason? So starting a project with ALL possibilities to come is a profound way of going bankrupt. If there would be multiple players needed, a singleton doe snot make sense. But you are just rying to prove a point with arguments, that are flying by randomly. Again, I understand this as a singleplayer game, so singleton fits to this target. If his plan is to make it coop, thats another story and another way of doing things.

leaden solstice
#

Relying on singleton is simply making your code inflexible for no good reason

hexed pecan
#

And judging the whole pattern if someone misuses it, is like hating hammers because someone hit their thumb with it

plucky inlet
#

Its giving you access to one source of truth of a specific class, good reason for me. Imagine having a datamanager load stuff or return textures you can load dynamically. You gonna hate singleton there too, because what if we want multiple datamanagers? (which does not make sense)

thin aurora
#

The only issue I have with singletons is that everybody resorts to implement it with a static variable. I feel like having a general provider that provides shared instances works a lot better here

plucky inlet
#

But I get, that you are not a fan of it and thats fine with me. Still I would love to read a suggestion / solution how you do it, so I can learn something new probably. Honestly always interested in other ways of doing stuff, if its not filled with raging subjectivity

thin aurora
#

That said, rejecting singletons because you might need more instances is a very obscure reason. You can give edge cases for everything, but that doesn't mean an implementation is bad

#

Just make sure you're not tied to it. Singletons are fairly reasy to scale on

leaden solstice
plucky inlet
#

Sounds like you continue with raging on me, so I step out of this conversation. No outcome for me here

thin aurora
#

If you have a main singleton provider that provides instances rather than a static variable everywhere then the code is very modular

hexed pecan
#

You can always make your singleton an interface and then swap out the implementation if needed
The reference needs to be stored somewhere tho

thin aurora
leaden solstice
#

Singleton registered to a IoC container is fine. It is not "singleton pattern"

#

Which imply access from static instance variable

hexed pecan
#

I haven't seen good arguments against using a static variable

#

And no i'm not talking about static in general, im talking about the singleton usecase

#

You also can't always assume that everyone develops for a massive team

thin aurora
#

There's nothing wrong with it, it works fine for the majority of people

#

There's always a better approach, and like everything else it has its issues

hexed pecan
#

Give me a concrete example of an issue

#

I'm ready to be educated

flat marsh
#

Does anyone have any good resources where I can learn about databases in relation to unity?

plucky inlet
#

For easier development to learn relations to data and your actual runtime object, I would go with some simple SO or inspector list to start off, testing around. Learning to serialise data from and to json. Database might be a bit too over the top to start off

leaden solstice
hexed pecan
thin aurora
flat marsh
plucky inlet
torn solar
#
void UpdateColors(Player targetPlayer = null)
{
    if (targetPlayer != null)
        playerList.transform.Find(targetPlayer.UserId).Find("Color").GetComponent<Image>().color = colors[(int) targetPlayer.CustomProperties["Color"]];
        
    HashSet<int> usedColors = new HashSet<int>();
    foreach (Player player in PhotonNetwork.PlayerList)
    {
        if (player.CustomProperties.ContainsKey("Color"))
        {
            usedColors.Add((int) player.CustomProperties["Color"]);
        }
    }
        
    foreach (GameObject color in colorButtons)
    {
        if (usedColors.Contains(colorButtons.ToList().IndexOf(color)))
        {
            if (color.GetComponent<Button>().interactable) color.GetComponent<Button>().interactable = false;
            if (!color.transform.Find("X").gameObject.activeSelf) color.transform.Find("X").gameObject.SetActive(true);
        }
        else
        {
            if (!color.GetComponent<Button>().interactable) color.GetComponent<Button>().interactable = true;
            if (color.transform.Find("X").gameObject.activeSelf) color.transform.Find("X").gameObject.SetActive(false);
        }
    }
}

i'm making a multiplayer game with photon pun where players select colors in the room, but when i'm updating the color buttons with this function, the buttons which are already claimed flicker (they become interactable and the X text on top of it gets disabled for a split second). how can i fix this?

leaden solstice
flat marsh
# plucky inlet In the end, your skilltree could be only ONE field in the database returning an ...

I mean its not too hard to add or subtract skills rn. To make a new skill, I just add an entry to one of the code paths (enum 2) , then add the else if statement under that branch in OnClickCheck(), and then I add what I want that skill point to do. Besides, before I actually made the skill tree I spent a while concepting out how I want it to work, so it should not be a huge amount of fiddling

plucky inlet
hexed pecan
flat marsh
leaden solstice
hexed pecan
#

With the same logic, you would always use float[] instead of float in your code, "in case you need more later"

#

(not related to your most recent message)

flat marsh
cold parrot
plucky inlet
#

yeh, might be the best answer. you are advancing everytime you learn something. So how much "advanced" are you, I do not know, but you are missing some core conecpts that you still have to learn. Not really a question, someone can easily answer from one script ๐Ÿ˜„

leaden solstice
cold parrot
#

Most people understand way less than they think they do and the more you understand the more you realize that you actually know nothing.

prime quarry
hexed pecan
#

Introducing people to new concepts or alternatives is totally okay, it just irks me when one says you "can't/shouldn't ever" use something, when it works for a lot of people's usecases

leaden solstice
swift falcon
#

Did you manage to continue ? I'm trying to do more or less the same thing

cold parrot
latent latch
#

I use player singletons when Im lazy and making a one-off game

cold parrot
#

I would encourage any team to figure out patterns that solve their specific workflow issues (from a team perspective) and be very sensitive to the actual dev experience and subtle nudges any such architecture decision produces

#

usually when cooperating with others in a project many things that make sense solo suddenly become a crippling liability. And there is a desire to find ways to restore that solo dev productivity.

torn solar
#
void UpdateColors(Player targetPlayer = null)
{
    if (targetPlayer != null)
        playerList.transform.Find(targetPlayer.UserId).Find("Color").GetComponent<Image>().color = colors[(int) targetPlayer.CustomProperties["Color"]];
        
    HashSet<int> usedColors = new HashSet<int>();
    foreach (Player player in PhotonNetwork.PlayerList)
    {
        if (player.CustomProperties.ContainsKey("Color"))
        {
            usedColors.Add((int) player.CustomProperties["Color"]);
        }
    }
        
    foreach (GameObject color in colorButtons)
    {
        if (usedColors.Contains(colorButtons.ToList().IndexOf(color)))
        {
            if (color.GetComponent<Button>().interactable) color.GetComponent<Button>().interactable = false;
            if (!color.transform.Find("X").gameObject.activeSelf) color.transform.Find("X").gameObject.SetActive(true);
        }
        else
        {
            if (!color.GetComponent<Button>().interactable) color.GetComponent<Button>().interactable = true;
            if (color.transform.Find("X").gameObject.activeSelf) color.transform.Find("X").gameObject.SetActive(false);
        }
    }
}

i'm making a multiplayer game with photon pun where players select colors in the room, but when i'm updating the color buttons with this function, the buttons which are already claimed flicker (they become interactable and the X text on top of it gets disabled for a split second). how can i fix this? i've tried rewriting the function in many different ways but it didn't help.

plucky inlet
latent latch
#

Singletons arent truely static though and have a lot more uses than just being some static accessor to some data. You can always just not flag it as Don't Destroy so when you load the next scene you can grab a whole new (specific) instance instantly from that same accessor

thin aurora
latent latch
#

And I feel like that's expect because there's no way to get any actual entry point to data when loading a new scene

plucky inlet
leaden solstice
thin aurora
#

You know one massive issue with singletons is that you can't depend on eachother. A provider would solve that too singe you grab your instances from a generally available location instead of having the risk that the singleton wasn't initialized yet

#

The only issue is ensuring the provider exists, which is a lot easier than fiddling with the order of everything else

#

TBH Unity should have had a Main method

cold parrot
hexed pecan
thin aurora
#

Which, note, by itself can use the whole singleton pattern. You have to do that anyway in order to access it

cold parrot
thin aurora
#

Yep, exactly

thin aurora
#

It's also that if you intend on changing the lifetime of objects, you can specify it in here before the provider has to start providing at all

leaden solstice
#

That is what most of DI libs use

thin aurora
#

.NET APIs also have a period where you can register dependencies before it runs

cold parrot
#

It boggles the mind that a service locator is such a trivially easy improvement over the singleton, yet nobody uses it and continues with the singleton nonsense for silly โ€˜convenienceโ€™ reasons.

thin aurora
#

I'd argue it's even easier

cold parrot
#

Also itโ€™s a very small step from a service locator to DI container if you later decide to go that way

plucky inlet
#

So you would have like a main ServiceLocatorClass that holds reference to all other providers and on the scripts accessing those providers, you now access the servicelocator.provider?

fathom cobalt
#

Hey all, could anyone help me figure out why my videoplayer does not have any audio? The video part plays just fine. I have it set up as follows

private VideoPlayer vp;
private AudioSource audioSource;

...

vp.audioOutputMode = VideoAudioOutputMode.AudioSource;
audioSource.volume = 1.0f;
vp.controlledAudioTrackCount = 1;
vp.EnableAudioTrack(0, true);
vp.SetTargetAudioSource(0, audioSource);

vp.Prepare();

yield return new WaitUntil(() => vp.isPrepared);

Debug.Log("Done preparing cutscene video");

vp.Play();
audioSource.Play();
latent latch
#

Yeah GameManager being the only singleton you need is probably the best way around it, but there's one issue with that and you end up with some very large variable accessors ;p

cold parrot
#

there is no need for the systems to know about the manager as a whole

leaden solstice
#

God class

cold parrot
#

systems should only depend on the bits of information that they actually need and that info should be injected

latent latch
#

Seems hard

cold parrot
latent latch
#

You expect that GameManager to know the state of the whole game at all times

cold parrot
#

you do the thing constantly, out of necessity, in all your normal code, you just never think about its directionality

latent latch
#

opposed to keeping some independency between the objects. I mean in a perfect project it would make sense but that seems like a lot of extra work

cold parrot
#

The game manager is just another system that also only knows the tiny bits that it must control

#

No system knows everything

#

the service locator or di container also just knows how to create or where to locate a service/resource but nothing of what it actually is

leaden solstice
cold parrot
#

Oh and if you feel this makes it annoying because you canโ€™t just call methods on anything at any time: thatโ€™s the whole point.

steady bobcat
#

just use 1 big script for your entire game /s (some guy on twtr did this :|)

latent latch
#

I'd probably have to look into that idea more. Feels like you'd abandon a lot of how Unity even works such as ignoring a lot of the instantiation calls.

cold parrot
steady bobcat
#

i wouldnt do this but i guess its certainly possible

cold parrot
#

the only situation where you need the service locator is for a component on a dynamically spawned object to find its managing system (usually part of a scene or other persistent context), register with it and receive all the remaining init/dependencies from there

azure frost
#

https://hastebin.skyra.pw/qorelonede.java
So, I'm having trouble with the Kinematic Character Controller's swim functions.

Using crouch and jump buttons don't descend and ascend like the walkthrough does. What am I doing wrong here?

steady bobcat
#

thankfully miside came along to save us (it uses unity 2021)

latent latch
reef garnet
covert dust
#

Okay, can someone please tell me the current working way of updating the mesh collider mesh at runtime? The project is an URP project in 2021.3.45

#

Tried a bunch of fixes from forums and none of them work 100% of the time.

reef garnet
hexed pecan
#

It's doable with some vector maths

#

How is the road mesh generated in the first place? Sidewalks generation wouldn't be too different from that

hexed pecan
#

And what issues did you run into?

covert dust
# hexed pecan And what issues did you run into?

I made procedurally generated terrain divided into 2x2 unit chunks. Each chunk creates a mesh that is used both for rendering and collision. When I use terrain destruction functionality, the rendering of the mesh updates but the collision sometimes doesn't.

hexed pecan
#

How do you modify the meshes, on gpu or cpu

#

(Also 2x2 is a weird chunk size ๐Ÿค” )

#

Or is that just the size in the world, but resolution is higher

covert dust
#

it's 100% CPU side at the moment

#

2x2 is the unit size, it's 12x12 vertices

#

it's a top down game so it doesn't really need more detail

hexed pecan
#

Are you sure you aren't passing invalid mesh data into the meshcollider

swift falcon
# reef garnet Unfortunately sidewalks are an unsolved problem

That's self intersecting polygon with the edges of your mesh, you could try different things to detect it. You could find if n and n+2 (or n, and n+ ... , non consecutives) edges intersects, or calculate winding number of diferents points on the left or right of each edge

hexed pecan
#

That should give some warnings at least

#

We can't help much without seeing the code or other details tbh

covert dust
#

to give a bit more context, this is called each time a mesh is recalculated:


    private void UpdateMesh()
    {
        if (_mesh == null)
            _mesh = new Mesh();
        _mesh.Clear();

        _mesh.vertices = _vertices;
        _mesh.triangles = _triangles;

        _mesh.RecalculateNormals();
    }

which should make sure the mesh is completely replaced with a new one I imagine? the _mesh variable is then applied to both mesh filter and collider

covert dust
hexed pecan
#

You might need to notify the physics engine about the mesh/collider changing somehow

#

@covert dust Try if something like this helps

meshCollider.sharedMesh = null;
meshCollider.sharedMesh = mesh;```
covert dust
#

I did as the first solution I found online

#

๐Ÿ˜†

#

as I said, none of them resulted in anything

#

some of them even worsened the problem

hexed pecan
#

Wdym "as i said"

#

How could i know you already tried this

covert dust
hexed pecan
#

Well, i didn't read any forum

#

Just thinking logically

covert dust
#

yeah sorry, that was literally the first google result ๐Ÿ˜

hexed pecan
#

When it happens, does the mesh collider seem to use the previous mesh data?

#

Or does it not work at all

#

And did you try messing with the cooking options (such as disabling all)

covert dust
#

okay, to make matters funnier, I reverted it to the pre-fix state and tried to reproduce the problem and it's not happening at all

#

๐Ÿ’€

covert dust
covert dust
hexed pecan
#

Wdym pre-fix state, what's different

covert dust
#

                // here it calculates new vertex heights

        UpdateMesh();
        _meshFilter.mesh = _mesh;
        _meshCollider.sharedMesh = _mesh;
covert dust
#

okay, it finally broke

#

took me like 5 minutes of nuking the map as I generate new chunks

vapid epoch
#

hi

thin aurora
#

And bye

pulsar plinth
#

soooo, a 2d sprite is just a plain rectangular mesh with a texture, right?

hexed pecan
#

You can see its triangles if you turn on wireframe mode in scene view

pulsar plinth
#

can I render a single 640x360 rectangular mesh for an entire screen, and draw textures inside it to optimize the game?

silent aspen
leaden solstice
steady bobcat
#

draw calls bad! so i will instead of an mega shader that somehow layers 100+ sprites together! /s

pulsar plinth
steady bobcat
#

Of course. gpus are able to handle many tris and batching helps combine many meshes to be drawn in 1 draw call

#

(the message was sarcasm btw)

pulsar plinth
#

ah I see

pulsar plinth
#

I'm still learning about meshes and textures
in fact, I'm actually starting to

west drum
#

guys can someone make a short tutorial about how to make a skilltree in unity

pulsar plinth
#

I think this depends on your game's speccific code a lot

west drum
#

how do you mean depends?

torn solar
#
void UpdateColors(Player targetPlayer = null)
{
    if (targetPlayer != null)
        playerList.transform.Find(targetPlayer.UserId).Find("Color").GetComponent<Image>().color = colors[(int) targetPlayer.CustomProperties["Color"]];
        
    HashSet<int> usedColors = new HashSet<int>();
    foreach (Player player in PhotonNetwork.PlayerList)
    {
        if (player.CustomProperties.ContainsKey("Color"))
        {
            usedColors.Add((int) player.CustomProperties["Color"]);
        }
    }
        
    foreach (GameObject color in colorButtons)
    {
        if (usedColors.Contains(colorButtons.ToList().IndexOf(color)))
        {
            if (color.GetComponent<Button>().interactable) color.GetComponent<Button>().interactable = false;
            if (!color.transform.Find("X").gameObject.activeSelf) color.transform.Find("X").gameObject.SetActive(true);
        }
        else
        {
            if (!color.GetComponent<Button>().interactable) color.GetComponent<Button>().interactable = true;
            if (color.transform.Find("X").gameObject.activeSelf) color.transform.Find("X").gameObject.SetActive(false);
        }
    }
}

i'm making a multiplayer game with photon pun where players select colors in the room, but when i'm updating the color buttons with this function, the buttons which are already claimed flicker (they become interactable and the X text on top of it gets disabled for a split second). how can i fix this? i've tried rewriting the function in many different ways but it didn't help.

leaden solstice
leaden solstice
#

Which you could get it for "free" if you just use for loop

leaden solstice
torn solar
#

alright imma record it

manic ether
#

Hello! Need some help reducing the size of my game.

The total user assets size is shown as : 31.7mb
but the total build size gets to 141 mb,
I have set Managed Stripping Level to High.
That has taken down 20 mbs as my build size was originally near 159mbs.
Done all the optimizations to assets as Images/Textures/Models, etc

Don't know what to do more to get the size down to around 50-60 mbs

leaden solstice
# torn solar

And is UpdateColors only place you are updating those?

torn solar
#

i feel dumb

#

i forgot about another function which runs when the player selects a color and i completely forgot about this part

#

tysm

vital salmon
#

hi hi how heavy is VR with regards to performance? My game renders many materials and gameobjects as well as lights. It probably won't be able to deal with VR

thin aurora
#

I have no idea what would be the best so you should probably just ask this in #๐Ÿ’ปโ”ƒunity-talk. People there probably point you to the correct one if needed

torn solar
# leaden solstice Which you could get it for "free" if you just use for loop
for (int i = 0; i < colorButtons.Length; i++)
{
    if (usedColors.Contains(i))
    {
        colorButtons[i].GetComponent<Button>().interactable = false;
        colorButtons[i].transform.Find("X").gameObject.SetActive(true);
    }
    else
    {
        colorButtons[i].GetComponent<Button>().interactable = true;
        colorButtons[i].transform.Find("X").gameObject.SetActive(false);
    }
}
#

is this okay?

leaden solstice
thin aurora
#

Also a styling note, you could simplify your code here because it only differs in the boolean. If you would like an example here I can provide it

#

I feel like you can make it even simpler considering usedColors appears to be a subset of colorButtons. Is it?

torn solar
thin aurora
#

Ah, then let's forget about that part ๐Ÿ˜„

torn solar
# leaden solstice Yeah, that looks much better. If you can reduce `GetComponent`/`Find` calls then...

i was thinking about creating these 2 variables to replace GetComponent and Find calls

[SerializeField] private Button[] colorButtonComponents;
[SerializeField] private GameObject[] colorClaimedOverlays;

i already had these 2 for the buttons and the colors before

[SerializeField] private GameObject[] colorButtons;
[SerializeField] private Color[] colors;

so would it be efficient to create a struct to combine these 4 variables?

leaden ice
#

Just use the button one

#

But yeah use a struct

torn solar
#

yeah i think i'll do that since i don't use colorButtons itself right now

leaden solstice
#

Then you can properly capsule what you do into methods like colorButtons[i].SetInteractable(!usedColors.Contains(i))

dusky lake
steady bobcat
#

nvm realised now you had this answered elsewhere

fast dune
#

I know that Debug.Log can be quite bad for performance. Would this be a good solution to remove Debug.Log from production builds?

namespace MyGame {

  public class Debug {

    public static void Log(string msg) {
        // we're in a production build
        if (!Application.isEditor && !UnityEngine.Debug.isDebugBuild) {
          return;
        } 

        UnityEngine.Debug.Log(msg);
    }

  }

}
thin aurora
#

I don't see why it would be bad for performance. Where did you find that info?

#

Generally the logging sink of Unity is always through this, or the ILogger which basically does the same (except keeping gameobject context)

steady bobcat
steady bobcat
#

logging a lot at runtime isnt good as it does write to various places and generate call stacks

thin aurora
#

You can always make a wrapper method and use the Conditional attribute which targets DEBUG

#

This way the method will be stripped out in builds, or applications without the DEBUG conditional

#

I suppose ideally you'd make a general logger that uses Debug.Log as its sink in DEBUG, but a different one in production. I can imagine you'd still want to log warning/error/critical level log message

#

Serilog works super well for this, and is the most popular approach

craggy veldt
#

Debug.log will do stack tracing and write to a file, it is surely bad

thin aurora
#
[Conditional("DEBUG")]
static void DebugDebugLog(string message)
{
  Debug.Log(message);
}

You get the idea

#

I'd use Serilog though. You can filter based on classes if done right so you can just turn off everything you don't need

fast dune
#

thanks!

craggy veldt
thin aurora
#

Still better than wrapping every single call in a conditional ๐Ÿ˜„

#

Omits the performance issue at least

fast dune
craggy veldt
#

it still exists in the IL on release

#

not that bad

thin aurora
#

It means that it's not fully stripped. Rather it checks on invoke if the method can be called

#

Which is a really negligible difference

#

.NET also has code contracts. I believe this is the real way of doing this. Never used it though.

#

Really goes over my head when I read these things

#

Oh, nevermind. This is for .NET Framework

#

No idea where I got this idea from then

thick terrace
#

code contracts are like the more powerful version of [NotNull] , [MaybeNullWhen] etc, they're just for verification

thin aurora
#

Been seeing them everywhere. I guess I was looking at really old code then

thick terrace
#

they're useful, you can specify that method doesn't return on some condition for example, which in IDEs like Rider will give you better warnings, like if you have an AssertNotNull method you can tell RIder it'll throw if you pass a null object in, therefore all usages of the object after that don't need a null check

#

i assume VS can do that too but i'm a Rider for life person lol

thin aurora
#

Note
Code contracts aren't supported in .NET 5+ (including .NET Core versions). Consider using Nullable reference types instead.

#

I wish I could ๐Ÿ˜›

thick terrace
#

well they work in Unity ๐Ÿ˜›

craggy veldt
#

you can alway polyfill them if it's not supported, it's not that hard

thick terrace
#

oh yeah in Unity it's provided by Jetbrains.Annotations

left void
#

My unity is taking too long to load empty scenes in async mode, spending 5 sec or more

plucky inlet
heady iris
#

I've noticed that a lot of the time spent on a scene load is actually from unloading another scene

#

including a big GC pause

rustic ember
#
Physics.Raycast(ray, out RaycastHit _hit, HUDSelectMaxDistance, HUDSelectLayermask))``` I want the Ray, the RaycastHit, and the LayerMask. If I remove the distance parameter, it treats the layermask as maxDistance. Do I just pass in Mathf.Infinity as the maxDistance, or is there a nicer way to do this?
rigid island
#

or just use the named parameters thing to arrainge your own order, you just need the correct amount of params

thick terrace
rustic ember
rustic ember
rigid island
rigid island
vestal arch
rigid island
# rustic ember ':'?

mhm that lets you place parameters in any order you want, but yeah you still need the same amount

vestal arch
#

if it were = it'd be ambiguous with an assignment

steady bobcat
#

foo(bar: 1)

rigid island
rustic ember
vestal arch
#

well you kinda are, but not through assignment

rustic ember
rigid island
#

each signature has its own order and number of params

rustic ember
rigid island
#

if it has = in the signature, it means you dont have to write anything cause it has default value

rustic ember
#

So since maxDistance has a default value, I don't have to write anything for that paramter?

rigid island
#

if you use a signature with a default value, you don't need to no

#

default iirc is mathf.inifinity

rustic ember
#

But then how does it know which signature I'm using?

#

This is really interesting

rigid island
#

Raycast has over 16 signatures

rustic ember
#

How do I doi the out thing?

vestal arch
hexed pecan
rigid island
#

Yeah you can just pass that again

rustic ember
vestal arch
#

named parameters just let you pass stuff out of order

rigid island
#

yeah you stil need the same amount , just can be placed in diff order

vestal arch
#

not sure how that relates to passing Mathf.Infinity to one of them

rustic ember
#

But what about the default valuesa then? They don't apply in that case?

rigid island
#

the signature you chosen probably didn't have default value

rustic ember
#

I'd still have to pass a maxDistance?

rigid island
#

the one with the out doesnt have a default value for max distance

#

so yes

rustic ember
#

It just says in the docs: cs public static bool Raycast(Vector3 origin, Vector3 direction, float maxDistance = Mathf.Infinity, int layerMask = DefaultRaycastLayers, QueryTriggerInteraction queryTriggerInteraction = QueryTriggerInteraction.UseGlobal);

rigid island
#

wrong signature

#

you're using the one with out

rustic ember
#

I see

rigid island
#

eg

public static bool Raycast(Vector3 origin, Vector3 direction, out RaycastHit hitInfo, float maxDistance, int layerMask, QueryTriggerInteraction queryTriggerInteraction); ```
rustic ember
#

Is there a reason that it doesn't have a default value like the other?

rigid island
#

no idea, thats something some unity dev thought of

#

just pass Mathf.Infinity same thing

rustic ember
#

Alrighty. Thank you for answering my many questions ๐Ÿ˜…

rigid island
#

np ๐Ÿ™‚

hexed pecan
#

The signature from the source code ```cs
static public bool Raycast(Vector3 origin, Vector3 direction, [DefaultValue("Mathf.Infinity")] float maxDistance, [DefaultValue("DefaultRaycastLayers")] int layerMask, [DefaultValue("QueryTriggerInteraction.UseGlobal")] QueryTriggerInteraction queryTriggerInteraction)

I wonder how defaultvalue attribute works
#

Some c++ shenanigans i guess

hexed root
hexed pecan
#

Also... aaaah

#

static public

#

Looks so wrong to me, i always do it the other way around

late lion
rigid island
#

lol oh wow its reversed

#

that threw me off for a sec

#

ohh its actually working.. huh TIL

late lion
#

Shows up here

rigid island
#

writing it flipped feels wrong

#

why did microsoft allow both ๐Ÿ˜›

hexed pecan
heady iris
#

I dunno why they did it this way instead of just having one definition with default values

#

Perhaps it's more convenient for other code generation

karmic stone
# rustic ember I see

so Axel, Raycast has 16 different methods, all named Raycast. c# knows which method to use based on what type of inputs you give it, what order its in, and how many inputs. For example foo(int num) and foo(string num) are declared in the same class. if you use foo(37) youll get int, and if you use foo("37") youll get the string method. This is called overloading a method, when you create different methods with same name, but different inputs.

polar marten
compact spire
#

If I have a large number of meshes (and colliders) under a single gameobject (which will have some physics applied to). From a performance standpoint does it make sense to merge those meshes together?

#

The meshes will share some common geometry so I should be able to remove a few faces here and there

polar marten
# compact spire If I have a large number of meshes (and colliders) under a single gameobject (wh...

Itโ€™s empirical. Thereโ€™s no hard and fast rule. https://assetstore.unity.com/packages/tools/modeling/mesh-combine-studio-2-101956 read the docs for this to understand more

Get the Mesh Combine Studio 2 package from Nathaniel Doldersum and speed up your game development process. Find this & other Modeling options on the Unity Asset Store.

pulsar plinth
#

so I've just used the multiple sprite mode in a sprite to accommodate a sprite sheet
what is the C# class which represents a multiple sprite mode sprite sheet?

#

the Sprite class only fits a single sprite in it, not a whole sheet

heady iris
#

The importer settings determine how the importer interprets your texture

#

when you use the "Multiple" mode, it creates more than one Sprite asset

#

There is no "multiple-sprite" type

pulsar plinth
#

ahhh I see, thank you

compact spire
#

@polar marten It could be a car, or plane, or boat. Boat I think has the more interesting complications, if using the mesh collider for calculating bouyancy

polar marten
#

it will explain all the limitations / what is required to get a performance boost from mesh combining

#

physics it's much simpler. the more colliders, and the more faces on those colliders, the more expensive collisions are to calculate.

north hatch
#

Does anyone know how to make a very smooth camera in unity

steady moat
north hatch
#

and clean movement

north hatch
north hatch
steady moat
pulsar plinth
leaden solstice
heady iris
#

each Sprite is an asset that tells you:

  • which texture to use
  • where to look on that texture
pulsar plinth
#

ahhhh, I see

#

I thought you meant each asset was its own texture

heady iris
#

Ah, no, that does not happen.

pulsar plinth
#

for context, I'm using DrawTexture instead of SpriteRenderer for optimization matters

polar marten
leaden solstice
polar marten
leaden solstice
#

Did you actually profile your game

polar marten
#

i don't think you have to worry about it.

leaden solstice
#

Or you just assume there will be perf issue

north hatch
polar marten
polar marten
pulsar plinth
polar marten
#

i wouldn't worry about it

leaden solstice
pulsar plinth
#

batching?

polar marten
#

it's not really possible to engage since this is all being written from scratch

leaden solstice
#

I see

pulsar plinth
#

yeah, exactly

polar marten
#

don't stress about it

leaden solstice
polar marten
#

i think you'll figure it all out

pulsar plinth
#

however, I'd still like to know what batching is

pulsar plinth
leaden solstice
pulsar plinth
#

does batching allow a sprite renderer to render more than 1 sprite at each frame?

leaden solstice
pulsar plinth
#

I see

rustic ember
#

Hi! I have a Vector3 that I need to rotate 90 degrees around another Vector3. How can I do this? I know I can multiply a Quaternion by a Vector3 to rotate the Vector3, but I have no idea how to do it

leaden solstice
#

Or rotate around as in the other vector as origin

rustic ember
rustic ember
#
Quaternion.AngleAxis(90, transform.forward) * vectorToRotate``` So this would work right?
#

I want to rotate the vectorToRotate 90 degrees around the objects forward axis

leaden solstice
rustic ember
leaden solstice
#

Yeah

rustic ember
#

Thank you so much ๐Ÿ™

wintry crescent
#

can I force passing a struct as a reference into an object type field?

latent latch
#

ref

wintry crescent
vestal arch
#

wouldn't you have to have ref on the other end, on the parameter?

#

or the struct, i forget

wintry crescent
wintry crescent
latent latch
#

what's the error

wintry crescent
leaden solstice
#

If you want to cast struct to object, you have to box

latent latch
#

oh right you've no typing on that

wintry crescent
# leaden solstice What are you trying to do

I have a dependency injection tool that is meant to use classes, but works with structs most of the time
unfortunately, to inject an already created object (rather than creating a new one) I have to pass in the object as a reference, since I'm not getting it back (result type void). It's meant to be a class, so it's not much of an issue... except I want it with a struct

leaden solstice
wintry crescent
leaden solstice
#

Oh you mean you are injecting into struct?

wintry crescent
#

yea

leaden solstice
wintry crescent
#

that's actually a big reason we moved to zenject in the first place

#

the issue is that it doesn't get returned if I'm trying to inject an already-existing object

leaden solstice
#

Actually you can.. eh

#
object copy = this;
Inject(copy);
this = (MyStruct)copy;

Could try something like this

latent latch
#

What if you did like some generic class wrapper and just passed the struct in

wintry crescent
#

uhoh that looks not good but I could try...

latent latch
#

I mean I guess that's technically boxing it too

wintry crescent
#

and the objects contained within the wrap won't get injected

#

which is rather sad but adding that functionality to zenject is way above my paygrade lmao

leaden solstice
#

Zenject is not really my favorite

#

Bit overcomplicated

wintry crescent
#

I have used a homegrown solution before, but that was too simple and too costly to expand

#

we had to rip it out and move to zenject because it was just too much work to maintain our own

#

ok, it was relatively advanced, but it had a million problems and zenject, most of the time, just works

#

zenject is a bit complex yes but also very powerful when you figure it out

cosmic fjord
#

hello everyone
how to make the parameter on my method become dynamic?

#

so it send the info of the clicked button

leaden solstice
leaden solstice
#

So it is kinda easy to mess up if you code without caution

wintry crescent
#

seriously, I have not had problems with it at all

leaden solstice
cosmic fjord
#

i made a parameter on my method of type " button"
when the player click one of these buttons i want to know the button clicked become the one in the parameter

#

sorry i mean i want the clicked button as the parameter button

#

never mind i did it the hard way ( it is not hard but i want to know the easy way for my info)

runic island
#

https://pastebin.com/drVDHZsE
I'm stupid or this is far more complicated than I gave it credit for. (Or both!)

I'm trying to get my AI to simply walk around a wall, stop within it's attack range, face the target (core) and then shoot. It sounds simple, no?
For some reason it walks around the wall, runs all the way through it's target, then faces the target (core) then shoots.

I'm so lost, I can't find a reason why it's acting like this although hopefully it's obvious to someone else. I'm on hour 3 trying various fixes, reading the navMesh API and I am just at a loss.

Help appreciated, thanks in advance.

runic island
leaden solstice
runic island
# leaden solstice Have you attached debugger and see if the code working as intended?

I've littered the code with debug.log statements if that's what you mean. It doesn't enter the else if() portion of the update function until it fully runs into the core for some reason.

My thought process is since this if statement is asked every frame it should update pretty much instantly when it's within the attackRange and stop moving via the second part of the code. The issue is that it's just not getting into that code until it's well past that point.

If debugger is a unity tool, I'm unfamiliar with it.

runic island
compact spire
#

To create trasnparent bullet holes in a mesh, would some sort of texture mask or shader be the best option?

#

modifying actual geometry seems.. expensive

wicked scroll
polar marten
polar marten
polar marten
#

i guess, why is it a struct at all if you need to inject it? just make it a class

#

struct --> class

wintry crescent
#

yeah I ended up doing that, but it doesn't really fit for it to be a class

#

but whatever

compact spire
#

@polar marten Yeah I want holes in my craft. This is in combination with the combined meshes from earlier. Goal is to build something out of some hull bits, merge such said thing into a mesh, put things into that mesh, then figure out some ways to represent an interesting damage state. Possibly with a combination of texture level stuff and if enough damage, maybe have things break in half using some mesh deformation....

#

It's.. a lot

polar marten
#

is the purpose of the game to have a destructible spaceship?

#

is that the game?

#

there's stuff that's more mechanical and sharper. you are looking for CSG assets. there aren't many though

#

you will also need a package called "vhacd" to create rigidbodies "with holes" (i.e. multiple rigidbodies of the correct mass)

compact spire
#

@polar marten More like from the depths.

#

Build all manner of craft, have them fight

polar marten
#

really depends on what you find interesting

#

take a look at mudbun ๐Ÿ™‚

compact spire
#

Well FtD ships are built out of a thousands of simple shapes, and destruction of the shape shows the damage. Elegant, but I'm going with scaleable shapes instead

#

That have a volume that you put things in

#

volumetric vfx... hmm

#

that seems like a completely different kind of direction

cold parrot
compact spire
#

@cold parrot That is fair, I feel that it's doable, it just depends on how many compromises I'm willing to make on my idea.

#

I'm just prototyping right now

#

I prototyped the building system as far as I need to, to get a feel how it's going t go

#

now I'm looking into performance feasibility for the physics and other interactions

cold parrot
#

what is the fundamental fun part of the game?

compact spire
#

Building your fleet of craft and then having it fight.

#

trying to scratch the same itch as From the Depths, Avorion, Stormworks ect

cold parrot
#

so "assemble stuff and watch it explode"?

compact spire
#

There is more beyond that, but that's the root of it

cold parrot
#

and how are you innovating and enhancing that?

compact spire
#

Those mechanics specifically? Different building system

cold parrot
#

i mean, why is your system more effective at scratching the itch?

compact spire
#

Less complex/ more efficient building system. Easier to build what you want. More of a focus on something a bit more rounded than FtD/Stormworks

cold parrot
#

will it also be prettier?

compact spire
#

I don't know. It should end up looking better than FtD

cold parrot
#

do you have maybe also have a stronger narrative or thematic hook?

compact spire
#

Stormworks has a clean aesthetic that I'm not really going for

#

narrative and theme are outside of what I'm prototyping

wicked scroll
#

so are there predefined modules that you kind of assumble into a big warship?

compact spire
#

Sort of

#

Imagine a lot of basic shapes, but you can scale them to make a hull

#

the hull has volume that you fill with things

wicked scroll
#

I'm not sure I'd bother with stuff at decal scale then. I think you'd want to predefine some 'fracture lines' in each shape and then decide how to break them based on incoming damage

compact spire
#

I'm playing around with mesh skewing to get even more customization out of the shapes

cold parrot
#

Well, i find this kind of game very interesting to make, but having made such a thing recently (a building game), its just a huge mountain of work. I would aim to keep stuff as simple as possible and search for a really strong twist on the basic idea that does not require you to have 1000s of build options, but as you said, thats basically what your innvation is, so it think thats a good one.

wicked scroll
#

whenever I try to design a ship-based combat game I get stuck on that the fantasy is really strong, but in practice, ship combat is actually very slow and binary in a way that makes it not very fun to watch and only marginally fun to participate in.

cold parrot
#

i would expect that if you make more free-form and rounded, non-grid, or not hotspot-snapped shapes you will explode your complexity

compact spire
#

@wicked scroll have you played From teh Depths?