cocos2d-iphoneccnode

CCNode recursive getChildByTag


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)


Solution

  • 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.