检查列表中gameObject的活动状态



我在一个列表中有4个gameObjects。我想从这个列表中检查活动游戏对象的数量。如果两个gameobject是活动的,那就意味着计数是2。计数的最好方法是什么?

public List<GameObject> Total_GO;
public void Start()
{
//Get Count of active gameObjects
}

您可以简单地使用LinqCount,并根据您的需要使用GameObject.activeInHierarchyGameObject.activeSelf作为过滤器

using System.Linq;
...
void Start()
{
// or obj.activeSelf according to your needs
var activeCount = Total_GO.Count(obj => obj.activeInHierarchy);
Debug.Log($"Active objects: {activeCount}", this);
}

或者如果你想要真正的使用活动对象使用LinqWhere

void Start()
{
// or obj.activeSelf according to your needs
var activeObjects = Total_GO.Where(obj => obj.activeInHierarchy).ToList();

var activeCount = activeObjects.Count;
Debug.Log($"Active objects: {activeCount}", this);
foreach(var obj in activeObjects)
{
...
}
}

相关内容

最新更新