unity 遍历 go 的一些方法

// 能找到所有的root go节点
GameObject[] allGos = UnityEngine.SceneManagement.SceneManager.GetActiveScene().GetRootGameObjects();

// 找不到隐藏的go
GameObject[] allGos = (GameObject[])UnityEngine.Object.FindObjectsOfType(typeof(GameObject));

// 连隐藏的go都能找到
GameObject[] pAllObjects = (GameObject[])Resources.FindObjectsOfTypeAll(typeof(GameObject));

Unity遍历一个 GameObject 的所有子物体,可以通过递归或非递归的方式实现。以下是一些常见的方法和代码示例: ### 方法一:使用 `foreach` 遍历直接子物体 Unity 提供了对 `Transform` 的迭代支持,可以直接通过 `foreach` 遍历当前对象的所有直接子物体[^2]。 ```csharp using UnityEngine; public class TraverseChildren : MonoBehaviour { void Start() { foreach (Transform child in transform) { Debug.Log("子物体名称: " + child.gameObject.name); } } } ``` 此方法遍历直接子物体,而不包括孙物体。 --- ### 方法二:递归遍历所有子物体(包括孙物体) 如果需要遍历所有的子物体(包括孙物体),可以使用递归函数来实现。以下是一个递归遍历的示例代码[^4]: ```csharp using UnityEngine; using System.Collections.Generic; public class RecursiveTraversal : MonoBehaviour { void Start() { List<Transform> allChildren = new List<Transform>(); GetAllChildren(transform, allChildren); foreach (Transform child in allChildren) { Debug.Log("所有子物体名称: " + child.gameObject.name); } } void GetAllChildren(Transform parent, List<Transform> children) { foreach (Transform child in parent) { children.Add(child); GetAllChildren(child, children); // 递归调用 } } } ``` 上述代码会递归地将所有子物体(包括孙物体)添加到列表中,并逐一打印它们的名称。 --- ### 方法三:非递归方式遍历所有子物体 除了递归外,还可以通过栈(Stack)或队列(Queue)实现非递归的遍历[^4]。以下是使用栈实现的示例: ```csharp using UnityEngine; using System.Collections.Generic; public class NonRecursiveTraversal : MonoBehaviour { void Start() { Stack<Transform> stack = new Stack<Transform>(); stack.Push(transform); while (stack.Count > 0) { Transform current = stack.Pop(); Debug.Log("当前物体名称: " + current.gameObject.name); foreach (Transform child in current) { stack.Push(child); // 将子物体压入栈中 } } } } ``` 该方法通过栈实现了与递归等效的功能,但避免了递归可能导致的栈溢出问题。 --- ### 方法四:遍历整个场景中的所有物体(包括隐藏物体) 如果需要遍历整个场景中的所有物体(包括隐藏物体),可以使用 `Resources.FindObjectsOfTypeAll` 方法[^3]。需要注意的是,此方法适用于编辑器环境,无法在运行时使用。 ```csharp using UnityEngine; using UnityEditor; public class SceneTraversal : MonoBehaviour { [MenuItem("Tools/遍历所有物体")] static void TraverseAllObjects() { GameObject[] allGameObjects = Resources.FindObjectsOfTypeAll<GameObject>(); foreach (GameObject go in allGameObjects) { if (go.hideFlags == HideFlags.None) // 过滤隐藏物体 { Debug.Log("物体名称: " + go.name); } } } } ``` --- ### 总结 - 如果只需要遍历直接子物体,可以使用 `foreach` 遍历 `transform`。 - 如果需要遍历所有子物体(包括孙物体),可以选择递归或非递归的方式。 - 如果需要遍历整个场景中的所有物体(包括隐藏物体),可以使用 `Resources.FindObjectsOfTypeAll` 方法,但仅限于编辑器环境。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值