¿Cómo apuntar a un CCSprite específico sin pasarlo al método?

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.

preguntado el 09 de marzo de 12 a las 14:03

They are just normal CCSprites which I have declared in other class (the one I call with [_hud hideThisActionLed:2];. It's a new class for HUD which shows all the info, health, turn counts etc. -

There are many possible ways to access the sprites. Can you edit your question and post the code you use to declare and add these sprites? -

2 Respuestas

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];

respondido 09 mar '12, 14:03

The first method works. Thank you! The second says "Incompatible pointer types initializing 'CCSprite *' with an expression of type 'CCNode *'. - Liuhu

When you add the CCSprite objects to your layer, use the withTag option. Then you can reference the sprites by the tag number which is the number you pass in to the hideThisActionLed method.

[_hud addChild:ledSprite withTag:1]; [_hud addChild:ledSprite2 withTag:2]; etc ...

-(void)hideThisActionLed:(int)ledNum {
CCSprite *theSprite = [_hud getChildByTag:ledNum];
... hide the sprite ...

respondido 09 mar '12, 14:03

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.