C# 两个If语句有一个常见的bool问题
我的脚本中有两个if语句和两个bool(bool1和bool2)-C# 两个If语句有一个常见的bool问题,c#,unity3d,C#,Unity3d,我的脚本中有两个if语句和两个bool(bool1和bool2)- using UnityEngine using system.collection public class example : MonoBehaviour { public bool bool1; public bool bool2; void Update() { if (bool1 == true) { // play animat
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
}
您必须更改订单的条件
void Update()
{
if (bool1 && bool2)
{
// play animation2
}
else if (bool1)
{
// play animation1
}
}
您可以进行一点嵌套,另外一个好处是bool1只需要评估一次:
if (bool1)
{
if (bool2)
{
// play animation2
}
else
{
// play animation1
}
}
if(bool1==true&&bool2==false)//播放动画1;if(bool1==true&&bool2==true)//播放动画2将bool与bool进行比较导致bool对我来说似乎很奇怪。您知道您可以简单地忽略
==true
?