Weird problem with randomness

So, I have this code for spawning an enemy every random amount of seconds

private void Update()
    {
        float rand = Random.Range(minCooldown, minCooldown + 1);
        if(rand + lastSpawn < Time.time)
        {
            lastSpawn = Time.time;
            GameObject go = Instantiate(prefab);
            go.transform.position = transform.position;
        }
    }

(minCooldown is set to 2 seconds)
However, I have a problem where the enemies always have a spawn cooldown of 2 - 2.3 seconds, tough it should be from 2 - 3 seconds.
I don’t get why this is happening and haven’t seen anyone else with this problem. Does anyone know what is going on? What should I do about this?

(Also, I’m not sure if I made this post in the right place. Please do correct me if I got it wrong)

Have you Debug.Log-ed the results and see what they average to?

Most likely the difference of values between 2-3 seconds isn’t particularly perceptible.

Yes I did. When I debug.log the rand variable outside the if statement, the values are normal (between 2 and 3). However, when I debug.log it inside the statement, the value is never higher than 2.5

Okay looking at your code, it’s logic is flawed. It’s making a random number every Update, so it will make a random value every frame, then check whether enough time has passed. So naturally, because of this behaviour, you will only see low value inside the if-statement.

When enough time has passed you need to make a randon value once and hold onto it, then rise and repeat that.

3 Likes

Wow, I had actually just noticed that and was about to update this post with this info. I now understand why this is happening, I will fix it tomorrow(it’s quite late rn). Thanks for the help, this solution ought to help a lot!

2 Likes