开发者

Cocos2d RemoveAllChildrenWithTag

开发者 https://www.devze.com 2023-02-21 06:14 出处:网络
I would like to have a method like -(void)removeAllChildrenWithTag:(int)tag in a CCNode-subclass. How would you do that?

I would like to have a method like -(void)removeAllChildrenWithTag:(int)tag in a CCNode-subclass. How would you do that?

I'm adding each round of my game some Sprites to this node and after the round is over I want to delete them. I thought giving all of them the same tag would be nice so I could just remove them by tag. But there is only a method to remove ONE child with a tag.

I know I could call this method until there is no child left but I think it would be slow. Is there any better solution like going throu开发者_如何学Cgh the whole children and removing each with the mentioned tag? I don't know how to do this because you can't remove any child in a for(* in *)-loop.

Hope you can help me. :)


Yeah.. I think iterating the children array and removing the specified tag children would be the easiest one. Here is some of the code.

CCNode *aChild;
while((aChild=[parentNode getChildByTag:aTag]) != nil)
    [parentNode removeChild:aChild cleanup:YES];


[self removeChildByTag:1 cleanup:YES];


This will remove only one child Here is the full implementation of the method

-(void) removeChildByTag:(int)aTag cleanup:(BOOL)cleanup
{
    NSAssert( aTag != kCCNodeTagInvalid, @"Invalid tag");

    CCNode *child = [self getChildByTag:aTag]; //here it is simply getting a single chil

    if (child == nil)
        CCLOG(@"cocos2d: removeChildByTag: child not found!");
    else
        [self removeChild:child cleanup:cleanup];
}


-(CCNode*) getChildByTag:(int) aTag
{
    NSAssert( aTag != kCCNodeTagInvalid, @"Invalid tag");

    CCNode *node;
    CCARRAY_FOREACH(children_, node){
        if( node.tag == aTag )
            return node; //as it finds the first child with the specified tag it will return
    }
    // not found
    return nil;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号