简体   繁体   中英

C# how to execute code before Thread.Sleep()? [RESOLVED]

    void SpaceBarUpdate() {

        if (Input.GetKeyDown("space") && timerStart == 0)   //if the timer isn't initialized and spacebar pressed
        {
            //txt.color = Color.red;

            UnityEngine.Debug.Log("Sleep started");
            Thread.Sleep(550);
            UnityEngine.Debug.Log("Sleep ended");


            if (Input.GetKey("space"))
            {
                UnityEngine.Debug.Log("Space down");

                // txt.color = Color.green;
                txt.text = "READY";

                //timerStart = 1;
            }

        }
    }

The output of this code is intended to be as follows, if the spacebar is pressed: (without the color formatting)

Sleep started
# delay of 550ms
Sleep ended

and then if the spacebar is still held down,

Space down

However, upon tapping the spacebar once, it outputs nothing for 550ms and then outputs this all at once: (again without the color formatting)

Sleep Started
Sleep ended
Space down

How do I get the "Sleep started" message to occur before the thread sleeps, and why is it progressing with the second if statement when I don't have the spacebar held down?

It does not work because the function .Sleep() pauses your program. Nothing is interpreted during that sleep time. If you want to be able to stop it, you must use an asynchrone method which is more advanced programming. You can read more about it in multiple sources online to learn.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM