C# Wait alternative/workaround?

So Im a super beginner coder and basically want a script to wait for 5 seconds before commencing the next line of code. I know there is no actual wait, but how could I incorporate something with that functionality into this simple script for example:

using UnityEngine;
using UnityEngine.UI;
using System.Collections;


public class RespawnTriggerText : MonoBehaviour {

    public Canvas respawning;
       
    void Start () {
            respawning.enabled = false;
        }
       
    void OnTriggerEnter(Collider other) {
            respawning.enabled = true;
                              // WAIT 5 SEC
                         //respawning.enabled = false;
    }
}

https://unity3d.com/learn/tutorials/modules/intermediate/scripting/coroutines

1 Like

As @roojerry linked, you can achieve that effect using coroutines. The code could look like this:

void OnTriggerEnter(Collider other)
{
     StartCoroutine( RespawnSequence() );
}

IEnumerator RespawnSequence()
{
     respawning.enabled = true;

     yield return new WaitForSeconds( 5f );

     respawning.enabled = false;
}

Do note, multiple OnTriggerEnter() would call multiple coroutines, which could lead to respawning.enabled setting to false even though you just entered again. You can store the coroutine as variable and manually stop it if it is running.

void OnTriggerEnter(Collider other)
{
     if (m_coroutine != null)
          StopCoroutine( m_coroutine );

     m_coroutine = StartCoroutine( RespawnSequence() );
}

Coroutine m_coroutine = null;
IEnumerator RespawnSequence()
{
     respawning.enabled = true;

     yield return new WaitForSeconds( 5f );

     respawning.enabled = false;
     m_coroutine = null;
}
2 Likes