简体   繁体   English

C#如何在Thread.Sleep()之前执行代码? [解决]

[英]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)但是,一旦点击空格键,它会在 550 毫秒内不输出任何内容,然后立即输出:(再次没有颜色格式)

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?如何在线程休眠之前让“睡眠开始”消息发生,以及为什么当我没有按住空格键时它会在第二个 if 语句中进行?

It does not work because the function .Sleep() pauses your program.它不起作用,因为函数.Sleep()暂停您的程序。 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.您可以在多个在线资源中阅读有关它的更多信息以进行学习。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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