Game Development Stack Exchange is a question and answer site for professional and independent game developers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.



share|improve this question
up vote 4 down vote accepted

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.

share|improve this answer
+1, but this assumes that you aren't adding child nodes that aren't sprites. – user744 Jul 24 '11 at 16:52
@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 – bummzack Jul 24 '11 at 18:03
In order to check if it's a CCSprite, I'm using [child isKindOfClass:[CCSprite class]] – Bob Rivers Jul 24 '11 at 18:31
@bummzack: The problem is that it "works" with nodes that aren't sprites, and the question is about how many sprites there are. – user744 Jul 24 '11 at 21:15
@Joe Wreschnig Oh yeah I see. Must have missed that part of the question. Will update accordingly. – bummzack Jul 24 '11 at 21:30

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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