WaitForSeconds and coroutine in unity | delaying a code action for some time in C#

 If you want to delay a code for few seconds in C# then you can use coroutine in unity. There are two methods of doing this -

WaitForSeconds() method

For creating a delay you first need to create a function of IEnumerator type and you can call it inside StartCoroutine() method when you want delay. let's see an example code 

using UnityEngine;

public class test : MonoBehaviour
{
    void Start()
    {
       StartCoroutine(Wait_Example());
    }

    IEnumerator Wait_Example()
    {
        Debug.Log(0);//run as soon as function run
        yield return new WaitForSeconds(4);
        Debug.Log("4");// run after 4 seconds
    }
}


  • In above example we have declare a function Wait_Example().
  • yield return new WaitForSeconds(4); this code will pause code written after it. Debug.Log("4"); run after time passed written in WaitForSeconds() function.
  • code written before WaitForSeconds() execute as soon as function run.
  • then WaitForSeconds() hold for given seconds
  • after time passed code written after WaitForSeconds() execute. So whatever code you want to run after a wait you can write it after WaitForSeconds().
  • We can only call this method inside StartCoroutine() method to run code.

  • WaitForSeconds calculate time according to sccaled time. It totally depend on timeScale means if timeScale is 1 then it is according to regular time but if we decrease or increase value of timeScale then time will be longer or shorter according to value.
  • For example if we pass 4 in WaitForrSeconds(4) and then we change timeScale to 0.2 then it will take around 20 secconds to execute code instead of 4. or if we change timeScale to 2 then it will take only 2 seconds to execute code instead of 4.
  • So for sometime it is our behavior but sometime not for that case we have WaitForSecondsRealtime.    

WaitForSecondsRealtime()

WaitForSecondRealtime() use unsccaledTime so as name suggest it does not depend on timeScale so whatever the value of timeScale is, it execute code at given time.

using UnityEngine;

public class test : MonoBehaviour
{
    void Start()
    {
       StartCoroutine(Wait_Example());
    }

    IEnumerator Wait_Example()
    {
        Debug.Log(0);
        yield return new WaitForSecondsRealtime(4);
        Debug.Log("4");
    }
}

   
Everything is same except we have used WaitForSecondsRealtime instead of WaitForSeconds.

Popular posts from this blog

Positioning GameObjects in unity editor

Creating count down timer in unity by c# script

Changing Image in unity by C# script