Search Unity

Making something happen after every x amount of time

Discussion in 'Scripting' started by Nuubzz, Oct 20, 2018.

  1. Nuubzz

    Nuubzz

    Joined:
    Aug 14, 2018
    Posts:
    31
    Hey, so I'm trying to make my game execute something after every x amount of time but I honestly have no idea how to do that.
    Could someone help me with that?

    Thanks in advance : D
     
  2. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    Invoke supports setting an amount of time to wait before calling the method, or use InvokeRepeating. In a coroutine it would be pretty simple to yield WaitForSeconds. You can also just set a float to Time.time + amountOfTimeToWait, and then check if that float is <= Time.time before you do something, then sent that float again to the next time you want to do something again.
     
    Nuubzz likes this.
  3. Nuubzz

    Nuubzz

    Joined:
    Aug 14, 2018
    Posts:
    31
    Ohhhh, okay!
    Thank you so much !!
     
  4. Joe-Censored

    Joe-Censored

    Joined:
    Mar 26, 2013
    Posts:
    11,847
    Just as a quick example of doing this using Update (which is usually the simplest way for people new to Unity to understand)

    Code (csharp):
    1. private float timeBetweenDoingSomething = 5f;  //Wait 5 seconds after we do something to do something again
    2. private float timeWhenWeNextDoSomething;  //The next time we do something
    3.  
    4. void Start()
    5. {
    6.     timeWhenWeNextDoSomething = Time.time + timeBetweenDoingSomething;
    7. }
    8.  
    9. void Update()
    10. {
    11.     if (timeWhenWeNextDoSomething <= Time.time)
    12.     {
    13.         //Do something here
    14.  
    15.         timeWhenWeNextDoSomething = Time.time + timeBetweenDoingSomething;
    16.     }
    17. }
     
    Nuubzz likes this.
  5. Nuubzz

    Nuubzz

    Joined:
    Aug 14, 2018
    Posts:
    31
    Yeah, it worked thanks !!