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

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

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)

有帮助吗?

解决方案

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;
}

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.

其他提示

Here would be a cocos2d-x 3.x implementation for a recursive getChildByTag function:

/** 
 * Recursively searches for a child node
 * @param typename T (optional): the type of the node searched for.
 * @param nodeTag: the tag of the node searched for.
 * @param parent: the initial parent node where the search should begin.
 */
template <typename T = cocos2d::Node*>
static inline T getChildByTagRecursively(const int nodeTag, cocos2d::Node* parent) {
    auto aNode = parent->getChildByTag(nodeTag);
    T nodeFound = dynamic_cast<T>(aNode);
    if (!nodeFound) {
        auto children = parent->getChildren();
        for (auto child : children)
        {
            nodeFound = getChildByTagRecursively<T>(nodeTag, child);
            if (nodeFound) break;
        }
    }
    return nodeFound;
}

As an option you can also pass in the type of the node searched for as an argument.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top