Home > Back-end >  Thread.Sleep & Task.Delay cause some parts of code to not work?
Thread.Sleep & Task.Delay cause some parts of code to not work?

Time:02-24

So I am trying to use this code:

        GetComponent<Renderer>().material.color = Color.red;
        Thread.Sleep(500);
        GetComponent<Renderer>().material.color = Color.white;

But when I do it, nothing happens; it appears, if I add a debug.log() it just prints it after 500ms even if the debug.log is before the thread.sleep, this also occurs with task.delay().

However, if I remove the Thread.Sleep or delay everything works normally color will change can confirm for the split second it changes in using debug.log.

So what is it about task.delay, or thread.sleep that causes the code near it not to run? And alternatively, is there a more efficient way to generate a wait before running the following line of code?

CodePudding user response:

You should be using WaitForSeconds in unity, not Thread.Sleep. If you were to sleep the main thread, your whole game would freeze. Read more here

You will need to create a coroutine.

public IEnumerator ChangeMaterialColorRoutine()
{
    var mat = GetComponent<Renderer>().material;

    mat.color = Color.red;

    yield return new WaitForSeconds(0.5f);

    mat.color = Color.white;
}

and you start the coroutine using StartCoroutine

StartCoroutine(
    ChangeMaterialColorRoutine()
);

Alternatively you can have a "timer" in Update that you add to each frame until the desired duration is met/exceeded.

private float waitTimer = 0;
private float timeToWait = 0.5f; // unit: seconds
private bool isWaitingForTimer = false;

void Update()
{
    if (isWaitingForTimer)
    {
        waitTimer  = Time.deltaTime; // add how much time passed since last frame

        if (waitTimer >= timeToWait)
        {
            waitTimer = 0;
            isWaitingForTimer = false;
        }
    }
}
  • Related