Search code examples
iphoneobjective-ccocos2d-iphoneccsprite

How to point to specific CCSprite without passing it to the method?


This is pretty simple question, but I'm having really hard time with it.

I have made a method which takes int variable. With it, it would need to use it to do action with CCSprite.

For example I call it with this: [_hud hideThisActionLed:2]; and it should then hide CCSprite named actionLed2.

I can't pass the actual CCSprite to the method, because I call it from another class which don't have access to that particular sprite.

I can make the sprite name with this: [NSString stringWithFormat:@"actionLed%d", actionLedNumber], but can't come up with a way to use that to point to that specified CCSprite.

Here's how I declared the sprites in hud class:

actionLed1 = [CCSprite spriteWithFrameName:@"actionLed1.png" setScale:TRUE resetAnchor:TRUE];
[actionLed1 setOpacity:0];
[self addChild: actionLed1 z:11 tag:1];

That x4 for all 4 leds.


Solution

  • This depends on how can access the different leds.

    If they are properties inside your class, then you can access them like this:

    NSString *actionLedName = [NSString stringWithFormat:@"actionLed%d", actionLedNumber];
    CCSprite *actionLed = [self valueForKey:actionLedName];
    

    If they are stored in an array, then you can access them like this:

    CCSprite *actionLed = [self.actionLeds objectAtIndex:actionLedNumber];
    

    If you have set up a tag for each actionLed when adding it, then you can access them like this:

    CCSprite *actionLed = [self getChildByTag:actionLedNumber];