以CocosCreator为例,Unity3D同理。这里提供三种获得子物体的方式。
public static Search(targetNode: cc.Node, name: string): cc.Node {if (targetNode.name &#61;&#61; name) {return targetNode;}for (let i &#61; 0; i < targetNode.children.length; i&#43;&#43;) {const child &#61; targetNode.children[i];let result &#61; this.Search(child, name);if (result !&#61; null) {return result;}}return null;}public static FindChildByName(targetNode: cc.Node, name: string): cc.Node {for (let i &#61; 0; i < targetNode.children.length; i&#43;&#43;) {const child &#61; targetNode.children[i];if (child.name &#61;&#61; name) {return child;}let result &#61; this.FindChildByName(child, name);if (result !&#61; null)return result;}return null;}public static FindChildByName2(targetNode: cc.Node, name: string): cc.Node {let queue: Queue<cc.Node> &#61; new Queue();queue.Enqueue(targetNode);while (queue.Count() > 0) {let t &#61; queue.Dequeue();if (t.name &#61;&#61; name) {if (t !&#61; targetNode) {return t;}}for (let i &#61; 0; i < t.children.length; i&#43;&#43;) {const element &#61; t.children[i];queue.Enqueue(element);}}return null;}
参考文档
https://answers.unity.com/questions/799429/transformfindstring-no-longer-finds-grandchild.html