0
\$\begingroup\$

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 =)

\$\endgroup\$
2
\$\begingroup\$

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++;
    }
}
\$\endgroup\$
0
\$\begingroup\$

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!

\$\endgroup\$

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.