Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice

Question Weird problem with randomness

Discussion in 'Scripting' started by Jirimias6, Feb 11, 2024.

  1. Jirimias6

    Jirimias6

    Joined:
    Jan 25, 2024
    Posts:
    5
    So, I have this code for spawning an enemy every random amount of seconds

    Code (CSharp):
    1. private void Update()
    2.     {
    3.         float rand = Random.Range(minCooldown, minCooldown + 1);
    4.         if(rand + lastSpawn < Time.time)
    5.         {
    6.             lastSpawn = Time.time;
    7.             GameObject go = Instantiate(prefab);
    8.             go.transform.position = transform.position;
    9.         }
    10.     }
    (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)
     
  2. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    7,786
    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.
     
  3. Jirimias6

    Jirimias6

    Joined:
    Jan 25, 2024
    Posts:
    5
    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
     
  4. spiney199

    spiney199

    Joined:
    Feb 11, 2021
    Posts:
    7,786
    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.
     
    Nad_B, Bunny83 and halley like this.
  5. Jirimias6

    Jirimias6

    Joined:
    Jan 25, 2024
    Posts:
    5
    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!
     
    Bunny83 and spiney199 like this.