如何在循环中检查 bool 是否为假
How to check if bool is false in a loop
我正在尝试遍历 classes 数组。 class 有两个变量:一个 transform 和一个 bool。
我想在另一个脚本中循环查看当前位置是否被占用,如果被占用,布尔值将被设置为真。
我该怎么做?
public Positions[] PosInObect = new Positions[1];
[System.Serializable]
public class Positions
{
public Transform pos;
public bool isFilled;
}
for (int i = 0; i < TheObject.GetComponent<GetInObject>().PosInObect.Length; i++)
{
}
嗯,你可以只访问相关索引处的元素,然后检查字段值:
if (TheObject.GetComponent<GetInObject>().PosInObect[i].isFilled)
但是,如果您不需要索引,我建议您使用 foreach
循环:
foreach (var position in TheObject.GetComponent<GetInObject>().PosInObect)
{
if (position.isFilled)
{
...
}
}
如果您确实需要这个位置,我会先使用局部变量来获取数组一次:
var positions = TheObject.GetComponent<GetInObject>().PosInObect;
for (int i = 0; i < positions.Length; i++)
{
if (positions[i].isFilled)
{
...
}
}
我还建议使用属性而不是 public 字段,并遵循 .NET 命名约定。
这可以在 foreach 循环中完成。您仍然可以从该 class 实例访问变量。
foreach(Positions pos in TheObject.GetComponent<GetInObject>().PosInObect)
{
if(pos.isFilled)
{
//Do something
}
}
我正在尝试遍历 classes 数组。 class 有两个变量:一个 transform 和一个 bool。
我想在另一个脚本中循环查看当前位置是否被占用,如果被占用,布尔值将被设置为真。
我该怎么做?
public Positions[] PosInObect = new Positions[1];
[System.Serializable]
public class Positions
{
public Transform pos;
public bool isFilled;
}
for (int i = 0; i < TheObject.GetComponent<GetInObject>().PosInObect.Length; i++)
{
}
嗯,你可以只访问相关索引处的元素,然后检查字段值:
if (TheObject.GetComponent<GetInObject>().PosInObect[i].isFilled)
但是,如果您不需要索引,我建议您使用 foreach
循环:
foreach (var position in TheObject.GetComponent<GetInObject>().PosInObect)
{
if (position.isFilled)
{
...
}
}
如果您确实需要这个位置,我会先使用局部变量来获取数组一次:
var positions = TheObject.GetComponent<GetInObject>().PosInObect;
for (int i = 0; i < positions.Length; i++)
{
if (positions[i].isFilled)
{
...
}
}
我还建议使用属性而不是 public 字段,并遵循 .NET 命名约定。
这可以在 foreach 循环中完成。您仍然可以从该 class 实例访问变量。
foreach(Positions pos in TheObject.GetComponent<GetInObject>().PosInObect)
{
if(pos.isFilled)
{
//Do something
}
}