我的脚本中有两个if语句和两个bools(bool1和bool2(。我的剧本是这样的——
using UnityEngine
using system.collection
public class example : MonoBehaviour
{
public bool bool1;
public bool bool2;
void Update()
{
if (bool1 == true)
{
// play animation1
}
if (bool1 == true && bool2 == true)
{
// play animation2
}
}
}
我只希望当两个布尔值都为真时播放 animation2,而不是同时播放 animation1 和 animation2。
我该怎么办?
您需要将语句重写为:
if (bool1 == true && bool2 == true)
{
// play animation2
}
else if (bool1 == true)
{
// play animation1
}
因为你的第一个陈述更有力,即当第二个陈述是正确的时它是真的,这就是为什么你需要反向检查你的条件。
大多数开发人员会省略== true
,因为它是不必要的。如果你想检查某事是否false
,你可以做!bool1
。这是您的代码,没有不必要的== true
:
if (bool1 && bool2)
{
// play animation2
}
else if (bool1)
{
// play animation1
}
你可以进行一些嵌套,还有一个额外的好处,你的 bool1 只需要被评估一次:
if (bool1)
{
if (bool2)
{
// play animation2
}
else
{
// play animation1
}
}
您必须更改条件顺序。
void Update()
{
if (bool1 && bool2)
{
// play animation2
}
else if (bool1)
{
// play animation1
}
}