首页 > 解决方案 > 如何在 C# 中检查玩家低于 y 坐标的时间

问题描述

我希望我的脚本检查玩家低于给定 y 坐标的时间。但是,由于我正在检查 FixedUpdate void 中的信息,因此无法直接添加 while 循环。因此,我尝试了以下方法:

void FixedUpdate()
{
if(rb.position.y < 1f)
        {
            checkIfLost();
        }
}

IEnumerator checkIfLost()
    {
        while(rb.position.y < 1f)
        {
            float timeGiven = 5 - Time.deltaTime;

            if(timeGiven <= 0)
            {
                FindObjectOfType<GameManager>().EndGame();
            }

            yield return null;
        }
    }

这不起作用。我是 Unity C# 的新手,我尝试在网上搜索它,但找不到任何东西。

运行 while 循环并检查玩家在 y 坐标下方的时间有什么更好的选择?

标签: c#unity3dif-statementwhile-loop

解决方案


只需将浮点变量设置为计数器

private float timer = 0f;

void FixedUpdate()
{
     if(rb.position.y < 1f)
     {
            timer +=Time.fixedDeltaTime;
            if (timer > 5f)
            {
                //do something
                FindObjectOfType<GameManager>().EndGame();
            }
     }
     else
     {
          timer = 0f;
     }
}

如果你想在更新(更好)中这样做,只需替换timer +=Time.DeltaTime;


推荐阅读