Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
231 views
in Technique[技术] by (71.8m points)

c# - Error with WaitHandle and Thread.Sleep

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);
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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");
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...