Reputation: 1290
I have a class that inherits from CCNode. I want to override the adding of this class to a parent.
So if ClassA inherits CCNode, I add it like this [self addChild:ClassA];
. ClassA contains 3 sprites and I want all 3 of those added when I add ClassA. Is there a way of doing this?
I looked into addChild
and saw that it calls setParent on the child, so in ClassA I override setParent to do this:
- (void) setParent:(CCNode *)parent {
[super setParent:parent];
[parent addChild:_sprite1 z:kZClassA];
[parent addChild:_sprite2 z:kZClassA];
[parent addChild:_sprite3 z:kZClassA];
}
Seems kinda hacky to me? Is there a better way of doing this?
Upvotes: 1
Views: 309
Reputation: 13713
There is no need to override addChild
for this task.
All you have to do is add the sprites when you create them in ClassA
. And when you will add ClassA
as a child of a node then ClassA children will be automatically added as well. (Since they are the children of ClassA
).
Assuming you create your sprites in the init method of ClassA
:
- (id) init {
if (self = [super init]) {
// Create the sprites and then :
[self addChild:sprite1]; // Add the sprite as a child of ClassA
[self addChild:sprite2];
[self addChild:sprite3];
}
return self;
}
then add classA
to the desired node (Probably a CCLayer
instance) :
[self addChild:classAInstance]; // Where self is an instance of your desired CCNode
Upvotes: 1