通过脚本获取游戏对象拥有的子代数 [英] Get number of children a game object has via script

查看:95
本文介绍了通过脚本获取游戏对象拥有的子代数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

标题说明了一切:通过脚本找出gameObject的子代数的最佳方法是什么.

Title says it all: What is the best way to find out how many children a gameObject has via script.

推荐答案

编辑1 :

一个简单变量 transform.hierarchyCount 已添加到 Unity 5.4 及更高版本.这应该可以简化这一点.

A simple variable transform.hierarchyCount, has been added to Unity 5.4 and above. This should simplify this.

Unity 5.3及更低版本的旧答案:

transform.childCount通常是执行此操作的方法,但它不会将孩子返回到该孩子的下方.它仅返回直接在GameObject transform.childCount下被调用的子级.就是这样.

transform.childCount provided by Adrea is usually the way to do this but it does not return a child under the child. It only returns a child that is directly under the GameObject transform.childCount is been called on. That's it.

要返回所有子游戏对象,无论是在另一个孩子的孩子之下还是另一个孩子的孩子之下,您都必须做更多的工作.

To return all the child GameObjects, whether under the child of another child which is under another child then you have to do some more work.

下面的函数可以计算子对象:

The function below can count child:

public int getChildren(GameObject obj)
{
    int count = 0;

    for (int i = 0; i < obj.transform.childCount; i++)
    {
        count++;
        counter(obj.transform.GetChild(i).gameObject, ref count);
    }
    return count;
}

private void counter(GameObject currentObj, ref int count)
{
    for (int i = 0; i < currentObj.transform.childCount; i++)
    {
        count++;
        counter(currentObj.transform.GetChild(i).gameObject, ref count);
    }
}

下面让我们说一下您的层次结构:

Let's say below is what your hierarchy looks like:

使用简单的测试脚本:

void Start()
{
    Debug.Log("Child Count: " + transform.childCount);
    int childs = getChildren(gameObject);
    Debug.Log("Child Count Custom: " + childs);
}

这是transform.childCount和自定义函数之间的结果:

This is the result between transform.childCount and the custom function:

孩子数:2

儿童计数自定义:9

因此,您可以看到transform.childCount不会计算child的孩子,而仅计算转换的孩子.自定义功能能够计算所有个子GameObject.

As, you can see the transform.childCount will not count childs of child but only child of the transform. The custom function was able to count all the child GameObjects.

这篇关于通过脚本获取游戏对象拥有的子代数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆