简体   繁体   中英

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);
    }
}

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

You will need to use Coroutines .

bool running;

IEnumerator DoWork(int time) 
{
    // Set the function as running
    running = true;
    
    // Do the job until running is set to false
    while (running)
    {
        // Do your code
        randomNumber();
        
        // wait for seconds
        yield return new WaitForSeconds(time);
    }
}

To call it use the following:

// Start the function on a 30 second time delay
StartCoroutine(DoWork(30));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM