这是在更新功能内。请原谅 brakeTorque
之类的东西,目前这只是一个创可贴。这是一款飙车游戏,Stated 意味着蓄势待发。一旦两辆车都上场,并且比赛尚未开始,那么应该有 5 秒的延迟,然后应该出现“GO 1”字样(我添加了 stupidCounter
作为调试工具)。然后它设置开始时间。然后它将 Racing 设置为 true,以防止再次跳回此 if
语句。
问题是它每帧都会在 if
语句中跳回;打印:GO1 GO2 GO3
等
在任何其他脚本中都没有提到“GO”这个词。 任何脚本中的其他任何地方都没有提到“Racing” bool 值。
这是我的代码:
if(Staged && OtherCarStaged() && !Racing)
{
RearRightWheel.brakeTorque = 10000;
RearLeftWheel.brakeTorque = 10000;
FrontRightWheel.brakeTorque = 10000;
FrontLeftWheel.brakeTorque = 10000;
yield WaitForSeconds(5);
stupidCounter += 1;
Debug.Log("GO " + stupidCounter);
mainTimerStart = Time.realtimeSinceStartup;
Racing = true;
}
最佳答案
我假设你的函数是一个协程。您的代码中的问题可能是因为您在每个更新帧中调用协程。您要么需要添加一个检查以仅调用协程一次,要么使用您自己的计时器而不是协程来处理此问题。
根据您提到的要求,我认为您的代码应该是这样的
var timeLeft : float = 5;
function Update()
{
StartCountdown();
}
function StartCountdown()
{
if(Staged && OtherCarStaged() && !Racing)
{
// your stuff
timeLeft -= Time.deltaTime;
if(timeLeft <= 0)
{
Debug.Log("GO");
mainTimerStart = Time.realtimeSinceStartup;
Racing = true;
}
}
}
或者,如果你想使用协程,那就像这样
function Update()
{
if(!countdownStarted && Staged && OtherCarStaged())
StartCoroutine(StartCountdown(5));
}
var countdownStarted : bool = false;
function StartCountdown(float time)
{
countdownStarted = true;
yield WaitForSeconds(time);
Debug.Log("GO ");
mainTimerStart = Time.realtimeSinceStartup;
Racing = true;
}
关于unity-game-engine - if 语句表现不佳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31509310/