如何在循环中检查bool是否为false

pvt*_*alt 0 c# loops for-loop class unity-game-engine

我正在尝试遍历一组类.该类有两个变量:变换和bool.

我想在另一个脚本中循环查看当前位置是否被占用,如果是,则bool占用将被设置为true.

我该怎么做呢?

 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++) 
 {

 }
Run Code Online (Sandbox Code Playgroud)

Jon*_*eet 9

好吧,您只需访问相关索引处的元素,然后检查字段值:

 if (TheObject.GetComponent<GetInObject>().PosInObect[i].isFilled)
Run Code Online (Sandbox Code Playgroud)

但是,如果您不需要索引,我建议使用foreach循环:

foreach (var position in TheObject.GetComponent<GetInObject>().PosInObect)
{
    if (position.isFilled)
    {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

如果你确实需要这个位置,我会先使用局部变量来获取数组:

var positions = TheObject.GetComponent<GetInObject>().PosInObect;
for (int i = 0; i < positions.Length; i++)
{
    if (positions[i].isFilled)
    {
        ...
    }
}
Run Code Online (Sandbox Code Playgroud)

我还建议使用属性而不是公共字段,并遵循.NET命名约定.