Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Resolved Fixed number of actions executed randomly in a time window

Discussion in 'Scripting' started by shanataru, Mar 4, 2021.

  1. shanataru

    shanataru

    Joined:
    Mar 4, 2019
    Posts:
    13
    Hello everyone,
    as the title suggests, I would like to execute an action 10 times during a time window (1 second). During this period I would like the actions to happen randomly (even some simultaneously would not be a problem) but at the end of each second, an average of 10 actions should be executed.

    I did a simple time check using Time.deltaTime and after every second I call the function 10 times, resulting in the actions executing all at the same time, which I do not want.

    What I am trying to do is a rainfall "simulation", where 10 raindrops fall down per second.

    Code (CSharp):
    1.     void Update()
    2.     {
    3.         t += Time.deltaTime;
    4.         if (t >= 1.0f) {
    5.             t = t - 1.0f;
    6.             Rain(); //contains a for loop for 10 actions
    7.         }
    8.     }
    I do not need a precise solution, so any suggestion is welcomed.
    Thank you.
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,762
    In your code above, why not change 1.0f to instead be 0.1f, then make "Rain()" only do one drop?
     
  3. Owen-Reynolds

    Owen-Reynolds

    Joined:
    Feb 15, 2012
    Posts:
    1,921
    So the idea in that code is to have uniformly spaced drops over time? Basically every 10th of a second 1 should drop? In that case, I think
    t+=Time.deltaTime*10;
    would be correct. It will add up to 10 over 1 second, and everytime it hits 1 a drop will fall.

    For a random approach, try this logic: suppose you're at 60FPS. That means we want 60*oddsOneDropEachFrame to equal 10, or oddsOneDropEachFrame=10/60. That 1/60 is time.deltaTime, so we get:
    if(Random.value<=10*Time.deltaTime)
    . A quick test, at 100FPS that gives 10*0.01 = 0.1.which is a 10% chance each frame. Over 100 frames that should give 10. Another sanity test, what it time.deltaTime*10>1? That means t.dt is 0.1 or more, which means we're at 10FPS or less. We want a 100% chance for a drop each frame!
     
    shanataru likes this.
  4. shanataru

    shanataru

    Joined:
    Mar 4, 2019
    Posts:
    13
    I am sorry I was not clear enough. I wanted the drops falling in the span of 1 second randomly in uniform distribution.

    The second approach is what I needed. It did not occur to me to deal with the FPS too.
    Thank you very much for all your responses.