•  

一、前言

这个问题还是比较简单的,无非就是一个for循环就可以全部获取到了,但是我喜欢简单直达,有没有直接就能获取到所有的子对象函数呢,搜了好久都没有,所以我准备写一个扩展函数,来自己补充这个函数,一起来看一下吧。

二、如何获取所有子对象

第一种方法:

使用foreach循环,找到transform下所有的子物体

foreach(Transform child in transform)
{
	Debug.Log();
}

比如说,我有一个父物体:m_ParObj,我如何获取到所有的子对象呢:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SplitTest : MonoBehaviour
{
    public GameObject m_ParObj;

    private void Start()
    {
        List<GameObject> m_Child = new List<GameObject>();
        foreach (Transform child in m_ParObj.transform)
        {
            //Debug.Log();
            m_Child.Add(child.gameObject);
        }
    }
}

这样就将所有的子对象保存了下来。

第二种方法:

通过transform.GetChild(i)来获取到所有的子对象:

for (int i = 0; i < transform.childCount; i++)
{
	Debug.Log(transform.GetChild(i).name);
}

比如说,我有一个父物体:m_ParObj,我如何获取到所有的子对象呢:

using UnityEngine;

public class SplitTest : MonoBehaviour
{
    public GameObject m_ParObj;

    private void Start()
    {
        GameObject[] m_Child = new GameObject[m_ParObj.transform.childCount];
        for (int i = 0; i < m_Child.Length; i++)
        {
            m_Child[i] = m_ParObj.transform.GetChild(i).gameObject;
        }
    }
}

这样就将所有的子对象保存了下来。

三、使用扩展方法获取所有子对象

总感觉获取个子对象还要用for循环有点麻烦,那么咱们就可以写一个扩展方法,直接获取到所有的子对象

1、首先新建一个MyExtensions.cs脚本

using System.Collections.Generic;
using UnityEngine;

public static class MyExtensions
{

}

2、编写脚本

using System.Collections.Generic;
using UnityEngine;

public static class MyExtensions
{
    public static List<GameObject> GetChild(this GameObject obj)
    {
        List<GameObject> tempArrayobj = new List<GameObject>();
        foreach (Transform child in obj.transform)
        {
            tempArrayobj.Add(child.gameObject);
        }
        return tempArrayobj;
    }

    public static GameObject[] GetChildArray(this GameObject obj)
    {
        GameObject[] tempArrayobj = new GameObject[obj.transform.childCount];
        for (int i = 0; i < obj.transform.childCount; i++)
        {
            tempArrayobj[i] = obj.transform.GetChild(i).gameObject;
        }
        return tempArrayobj;
    }
}

这有两个函数,一个是获取所有子对象的List集合,一个是获取所有子对象的数组集合,按需使用。

扩展方法的使用可以参考我这篇文章:
【Unity3D日常开发】扩展方法的使用

3、使用扩展方法
使用m_ParObj.GetChild()就可以调用扩展方法:

using System.Collections.Generic;
using UnityEngine;

public class SplitTest : MonoBehaviour
{
    public GameObject m_ParObj;

    private void Start()
    {
        List<GameObject> m_Child = m_ParObj.GetChild();
        for (int i = 0; i < m_Child.Count; i++)
        {
            Debug.Log(m_Child[i].);
        }
    }
}

这样就可以通过一个函数就可以获取到所有的子对象了。