[CocosCreator][Unity]获得子物体的方法(递归,深度优先,广度优先)

以CocosCreator为例,Unity3D同理。这里提供三种获得子物体的方式。

/**
     * 从目标节点及其子孙节点中找到满足`name`的节点.
     * 未找到满足条件的,返回null
     * @param targetNode 
     * @param name 
     */
    public static Search(targetNode: cc.Node, name: string): cc.Node {
        if (targetNode.name == name) {
            return targetNode;
        }

        for (let i = 0; i < targetNode.children.length; i++) {
            const child = targetNode.children[i];
            let result = this.Search(child, name);
            if (result != null) {
                return result;
            }
        }

        return null;
    }


    /**
     * 从子孙节点中找到第一个名字符合的节点,不包括目标节点本身。
     * 使用 深度优先的方式。
     * 若没有找到,则返回null
     * @param targetNode 
     * @param name 
     */
    public static FindChildByName(targetNode: cc.Node, name: string): cc.Node {
        for (let i = 0; i < targetNode.children.length; i++) {
            const child = targetNode.children[i];
            if (child.name == name) {
                return child;
            }

            let result = this.FindChildByName(child, name);
            if (result != null)
                return result;
        }
        return null;
    }


    /**
     * 从子孙节点中找到第一个名字符合的节点,不包括targetNode节点本身。
     * 使用 广度优先的方式。
     * 若没有找到,则返回null
     * @param targetNode 
     * @param name 
     */
    public static FindChildByName2(targetNode: cc.Node, name: string): cc.Node {
        let queue: Queue<cc.Node> = new Queue();
        queue.Enqueue(targetNode);

        while (queue.Count() > 0) {
            let t = queue.Dequeue();
            if (t.name == name) {
                if (t != targetNode) {
                    return t;
                }
            }
            for (let i = 0; i < t.children.length; i++) {
                const element = t.children[i];
                queue.Enqueue(element);
            }
        }

        return null;
    }

参考文档

https://answers.unity.com/questions/799429/transformfindstring-no-longer-finds-grandchild.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

iningwei

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值