Search code examples
c#unity-game-enginetimer

How to repeat an action each X seconds in Unity C#


I want the action "randomNumber" to happen once every 30 seconds.

public class INScript : MonoBehaviour
{
    int rnd;

    void Start()
    {
         Invoke("randomNumber", 30);   
    }

    public void randomNumber()
    {
        rnd = Random.Range(0, 100);
        Debug.Log(rnd);
    }
}

Solution

  • You can use InvokeRepeating to achieve it. In your case it would look something like this:

    void Start()
    {
         InvokeRepeating("randomNumber", 0, 30);   
    }
    

    Where 0 is the initial delay before the method is called (So, instant) and 30 is every 30 seconds that method will be repeated