跟踪游戏对象的子级数量

Keeping track of the number of Children of a GameObject

我写了这段代码来计算场景中 GameObject 的子项。它有效,但感觉不像是最优雅的解决方案(特别是我每次都将 childCount 重置为 0 的那一行)。有人可以给我一些重写建议以使其更精简吗?

public int childCount;

public void countChildren() 
{
    GameObject buildBoard = GameObject.FindGameObjectWithTag("Board");

    GameObject[] allChildren = buildBoard.transform.Cast<Transform>().Select(t=>t.gameObject).ToArray();

    childCount = 0;

    for(int i = 0; i < allChildren.Length; i++)
    {
        childCount++;
    }

    Debug.Log(childCount);
}

我认为您不必强制转换为 Transform,因为 GameObject.transform already returns Transform type. And Transform already has Transform.childCount 方法。所以你可以这样数:

public int childCount;
public void countChildren() 
{
    GameObject buildBoard = GameObject.FindGameObjectWithTag("Board");

    childCount = buildBoard.transform.childCount;

    Debug.Log(childCount);
}

你也可以把它包装成一个小辅助方法:

public int CountChildrenForObjectWithTag(string tag)
{
    var gameObject = GameObject.FindGameObjectWithTag(tag);

    if (gameObject == null || gameObject.transform == null) return 0;

    return gameObject.transform.childCount;
}

您可以在游戏对象中创建一个静态变量 class。每次添加或删除任何内容时,您都可以在 class 中进行内部更新。这个静态变量在每个 GameObject 中都是一致的,如果其中任何一个发生变化,都会反映出来。通过提供只读 属性,您可以从任何对象访问此计数。

public class GameObject
{
    private static int childrenCount = 0;
    public int ChildrenCount { get { return childrenCount; } }

    // the rest of your logic
}