Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

Pretty simple question. I'm working in Objective C (cocos2d) and I'm trying to count the number of a sprites of a certain class are present on the current layer being displayed. For example, I have a class named Seal which is a subclass of of CCNode and in my current layer I want to count how many instances of type Seal are present.

I know how to count the number of children of the layer by doing

int numberChildren = [[self children] count];

which correctly returns the number of children on the layer. But I just want the number of Seals on my layer. How could I do this? Thanks =)

share|improve this question

2 Answers 2

up vote 2 down vote accepted

Do as ryrich said, however the actual code on Objective-C would be something like this: (Assuming your CCNode class is called "Seal")

int sealCounter = 0;
for (id *node in self.children) {
    if ([node isKindOfClass:[Seal class]]) {
        sealCounter++;
    }
}
share|improve this answer

I come from a C# background, so I can't write you the code (don't want to give you gross, translated Objective-C code :))

But what you could do is loop through the Children ([self children]), check if they can be casted as a Seal. If the casted object is not null, increment a counter. Then just return the counter after the loop is finished.

Hope this helps!

share|improve this answer

Your Answer

 
discard

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.