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

时间:2019-12-27 03:58:36

标签: c# thread-sleep

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

        }
    }

如果按下空格键,则此代码的输出应如下所示: 颜色格式)

Sleep started
# delay of 550ms
Sleep ended

,然后如果仍然按住空格键,

Space down

但是,一旦按一下空格键,它将在550ms内什么都不输出,然后一次全部输出:(同样,不进行颜色格式化)

Sleep Started
Sleep ended
Space down

如何使“睡眠开始”消息出现在线程睡眠之前? ?为什么当我没有按住空格键时,为什么使用第二个if语句进行处理? >

1 个答案:

答案 0 :(得分:0)

它不起作用,因为函数.Sleep()暂停了程序。在那个睡眠时间内,没有任何解释。如果要停止它,则必须使用异步方法,该方法是更高级的编程。您可以从多个在线资源中阅读有关它的更多信息以进行学习。

相关问题