CCNode 递归 getChildByTag递归、CCNode、getChildByTag

2023-09-06 10:41:22 作者:粉蝶翩翩飞

据我了解 CCNode::getChildByTag 方法仅在直接子代中搜索.

As far as I understand the CCNode::getChildByTag method only searches among direct children.

但是有什么方法可以通过标签在其所有后代层次结构中递归查找 CCNode 的子节点?

But is there any way to recursively find a CCNode's child by tag in all its descendant hierarchy ?

我正在从一个 CocosBuilder ccb 文件中加载一个 CCNode,我想检索只知道它们的标签(而不是它们在层次结构中的位置/级别)的子节点

I'm loading a CCNode from a CocosBuilder ccb file and I'd like to retrieve subnodes knowing only their tags (not their position/level in the hierarchy)

推荐答案

一种方法——创建自己的方法.或使用此方法为 CCNode 创建类别.它看起来像这样

One way - to create your own method. Or create category for CCNode with this method. It will look like smth like this

- (CCNode*) getChildByTagRecursive:(int) tag
{
    CCNode* result = [self getChildByTag:tag];

    if( result == nil )
    {
        for(CCNode* child in [self children])
        {
            result = [child getChildByTagRecursive:tag];
            if( result != nil )
            {
                break;
            }
        }
    }

    return result;
}

将此方法添加到 CCNode 类别.您可以在所需的任何文件中创建类别,但我建议仅使用此类别创建单独的文件.在这种情况下,将导入此标头的任何其他对象都可以将此消息发送到任何 CCNode 子类.

Add this method to the CCNode category. You can create category in any file you want but I recommend to create separate file with this category only. In this case any other object where this header will be imported, will be able to send this message to any CCNode subclass.

实际上,任何对象都可以发送此消息,但如果不导入标头,则会在编译过程中引起警告.

Actually, any object will be able to send this message but it will cause warnings during compilation in case of not importing header.