1. 递归
函数体逻辑包含调用自身的函数,称为递归函数
但是!!
如果数据量比较大,短时间内可能会造成函数不断压栈,浪费性能。
递归可以理解成一个死循环,当不满足条件时,停止循环
所以这里提供一个堆栈写法,来优化递归
2. 查找子物体
2.1 递归写法
private Transform FindChild(Transform root, string childName)
{
var trans = root.Find(childName);
if (trans != null)
return trans;
if (root.childCount != 0)
{
for (int i = 0; i < root.childCount; i++)
{
trans = FindChild(root.GetChild(i), childName);
if (trans != null)
return trans;
}
}
return null;
}
2.2 堆栈写法
Stack<Transform> stack = new Stack<Transform>();
private Transform FindChild2(Transform root, string childName)
{
stack.Push(root);
while (stack.Count > 0)
{
root = stack.Pop();
var trans = root.Find(childName);
if (trans != null)
return trans;
for (int i = 0; i < root.childCount; i++)
{
stack.Push(root.GetChild(i));
}
}
return null;
}
总结:一遍逻辑,操作入栈
3. 完整代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class TransformUtility : MonoBehaviour
{
void Start()
{
var res = FindChild2(transform, "Image (1)");
if (res != null)
{
Debug.LogError("找到了 Image (1)");
Debug.LogError($"{res.name}");
}
}
private Transform FindChild(Transform root, string childName)
{
var trans = root.Find(childName);
if (trans != null)
return trans;
if (root.childCount != 0)
{
for (int i = 0; i < root.childCount; i++)
{
trans = FindChild(root.GetChild(i), childName);
if (trans != null)
return trans;
}
}
return null;
}
Stack<Transform> stack = new Stack<Transform>();
private Transform FindChild2(Transform root, string childName)
{
stack.Push(root);
while (stack.Count > 0)
{
root = stack.Pop();
var trans = root.Find(childName);
if (trans != null)
return trans;
for (int i = 0; i < root.childCount; i++)
{
stack.Push(root.GetChild(i));
}
}
return null;
}
}