Does cocos2d has a method that returns the amount of CCSprites added to a CCLayer?

A have SceneControlLayer object, and I added some CCSprites to it.

@interface SceneControlLayer : CCLayer {

@implementation SceneControlLayer

-(id)init {

CCSprite *spr1 = [CCSprite spriteWithFile:@"spr1.png];
[self addChild:spr1 z:1 tag:1];

CCSprite *spr2 = [CCSprite spriteWithFile:@"spr2.png];
[self addChild:spr2 z:2 tag:2];



How do I retrieve an array of sprites added to the layer? Could I retrieve all the objects added through addChild and test its type?

Since I'm starting with cocos2d/objectivec, please, give some examples how to do it...

I also thought that I could create an array, and, besides adding it to the layer, add it to the array also. But I'm not so sure if it's a good option.




Every CCNode has a children property, which is a CCArray, containing all children. Since CCLayer is a subclass of CCNode, you can get the number of children added to the layer using: [[layer children] count]

Update: If you're not checking that sprite count very frequently, you can simply iterate through the children array and count the number of children that are actually sprites (using isKindOfClass). If you need to access these sprites constantly (eg. in every update) it would probably be wiser to also store them in a separate array.

| improve this answer | |
  • 1
    \$\begingroup\$ +1, but this assumes that you aren't adding child nodes that aren't sprites. \$\endgroup\$ – user744 Jul 24 '11 at 16:52
  • \$\begingroup\$ @Joe Wreschnig: I don't understand. Why wouldn't it work with nodes other than sprites? It should work with any object that derives from CCNode \$\endgroup\$ – bummzack Jul 24 '11 at 18:03
  • \$\begingroup\$ In order to check if it's a CCSprite, I'm using [child isKindOfClass:[CCSprite class]] \$\endgroup\$ – Bob Rivers Jul 24 '11 at 18:31
  • 1
    \$\begingroup\$ @bummzack: The problem is that it "works" with nodes that aren't sprites, and the question is about how many sprites there are. \$\endgroup\$ – user744 Jul 24 '11 at 21:15
  • \$\begingroup\$ @Joe Wreschnig Oh yeah I see. Must have missed that part of the question. Will update accordingly. \$\endgroup\$ – bummzack Jul 24 '11 at 21:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.