Error with WaitHandle and Thread.Sleep

梦想与她 提交于 2019-12-13 08:46:27

问题


I looked around on here for a way to make my script wait a few seconds and found this article which people recommended. I took some of this code and used it in my game to make it wait but it doesn't act as I want it to. I placed it between two Debug.Log lines but it waits for the designated time and then logs both things at once instead of waiting after the first has triggered.

static void Waiter(){
    waitHandle.WaitOne ();
}
Debug.Log (choice);

new Thread (Waiter).Start ();   
Thread.Sleep (5000);
waitHandle.Set ();

Debug.Log (enemyChoice);

回答1:


To wait in Unity, you use coroutine and WaitForSeconds. You can also use coroutine with Time.deltaTime or Time.time but the simplest way to do this is to use WaitForSeconds. Note that if you wait with Thread.Sleep, your whole program will freeze. Don't do that because the UI will not be responsive too.

void Start()
{
    StartCoroutine(doSomethingThenWait());
}

IEnumerator doSomethingThenWait()
{
    UnityEngine.Debug.Log("Before Waiting");
    //Wait for 2 Seconds
    yield return new WaitForSeconds(2);
    UnityEngine.Debug.Log("After Waiting");
}


来源:https://stackoverflow.com/questions/44232352/error-with-waithandle-and-thread-sleep

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!