首页 > 解决方案 > 如何在 C#/Unity 中等待一段时间而不冻结代码?

问题描述

我正在制作一个练习游戏,以习惯在必须射鸟的地方编码。当子弹用完时,您需要按“r”键重新加载子弹。我希望在按下按钮和重新加载子弹之间有一个延迟,但到目前为止我发现的是冻结所有内容的代码(如下所示)。有没有办法防止代码冻结一切?摘要:当按下“r”按钮时,下面的代码会冻结所有内容(整个游戏)。是否有我可以使用的代码不会冻结所有内容,并且只会等待 2 秒才能运行下一个操作?

    IEnumerator TimerRoutine()
    {
        if (Input.GetKeyDown(KeyCode.R))
        {
            yield return new WaitForSeconds(2);   //Fix this, freezes everything
            activeBullets = 0;
        }
    }

标签: c#unity3d

解决方案


使用协程来设置这个延迟

    if (Input.GetKeyDown(KeyCode.R) && isDelayDone) // defined isDelayDone as private bool = true;
    {
        // When you press the Key
        isDelayDone = false;

        StartCoroutine(Delay());
        IEnumerator Delay()
        {
            yield return new WaitForSeconds(2);
            isDelayDone = true;
            activeBullets = 0;
        }
    }

推荐阅读