Create an endless loop in Unity with a delay

Do I need to create an infinite loop in Unity without using the main thread? I saw a few examples, but this is not useful:

while(true){
         var aa;
         debug.log("print.");
} 

I want to add some delay, for example, for example. 2 seconds If anyone knows a solution, please help.

+4
source share
3 answers

Use this to create a loop;

private IEnumerator LoopFunction(float waitTime)
{
    while (true)
    {
        Debug.Log("print.");
        yield return new WaitForSeconds(waitTime);
        //Second Log show passed waitTime (waitTime is float type value ) 
        Debug.Log("print1.");
    }
}

To call a function, do not use Update()or FixedUpdate(), use something like Start()so as not to create infinite loop instances;

 void Start()
 {
      StartCoroutine(LoopFunction(1));
 }
+2
source

First define Coroutines :

private IEnumerator InfiniteLoop()
{
    WaitForSeconds waitTime = new WaitForSeconds(2);
    while (true)
    {
        //var aa;
        Debug.Log("print.");
        yield return waitTime;
    }
}

Then name it like this:

 StartCoroutine(InfiniteLoop());

Note added:

Time.timeScale , , :

yield return new WaitForSecondsRealtime(2);
+8

Use coroutines ..

//Call in your Method
StartCoroutine(LateStart(2.0f));

Then write a coroutine like ..

private IEnumerator LateStart(float waitTime)
{
    yield return new WaitForSeconds(waitTime);

    //After waitTime, you can use InvokeRepeating() for infinite loop infinite loop or you use a while(true) loop here
    InvokeRepeating("YourRepeatingMethod", 0.0f, 1.0f);
}

Here is the documentation for InvokeRepeating (): https://docs.unity3d.com/ScriptReference/MonoBehaviour.InvokeRepeating.html

0
source

Source: https://habr.com/ru/post/1663510/


All Articles