ahoura
ahoura

Reputation: 689

how to update a value without adding it as a child to a scene

so i am trying to update the score in my game, and the code is running fine but the structure doesnt seem right to me. what I am doing right now is keeping the score in a var and then removing the old child and adding a new child to update the score, something like :

if([self awake]){
    int score = (int) x;
    //NSLog(@"%i", score);

    CCLabelBMFont * scoreLabel = [CCLabelBMFont labelWithString:[NSString stringWithFormat:@"Score : %d", score] fntFile:@"good_dog_plain_32.fnt"];
    scoreLabel.position = ccp(100, 300);
    [scoreScene addChild:scoreLabel];

        if([_game getChildByTag:123]){
            [_game removeChildByTag:123 cleanup:YES];
        }
    [_game addChild:scoreScene z:99 tag:123];
}

now this code works just fine but its ruining the fps for the game!!! is there anyway I can update the value of scoreLabel without having to remove and then add the score to the main scene of the game?

thanks

UPDATED CODE final fixed code :

in the main layer of the game I added

CCLabelBMFont * scoreLabel;

in the header file.

in the main init of the game I added

int score = 0;
        scoreLabel = [CCLabelBMFont labelWithString:[NSString stringWithFormat:@"Score : %d", score] fntFile:@"good_dog_plain_32.fnt"];

        CCScene * scoreScene = [CCScene node];
        scoreLabel.position = ccp(100, 300);
        [scoreScene addChild:scoreLabel];
        [self addChild:scoreScene z:99 tag:123];

and then simply used setString in my method to update the score like :

 [_game.scoreLabel setString:[NSString stringWithFormat:@"Score : %d", score]];

note that _game is because I declared the scoreLabel in the main scene, and my method is running in another file, so if you have your highscore method in the same file, there is no need for _game

Upvotes: 1

Views: 336

Answers (2)

Yannick Loriot
Yannick Loriot

Reputation: 7136

The CCLabelBMFont implement the CCLabelProtocol, so it's respond to the setString: method.

You just have to had your "scoreLabel" in the init method and then update the score like that:

if([self awake])
{
    int score = (int) x;
    //NSLog(@"%i", score);

    [scoreLabel setString:[NSString stringWithFormat:@"Score : %d", score]];
}

EDIT

It can looks like that:

- (id)init
{
   if ((self = [super init]))
   {
      self.score = 0;

      CCLabelBMFont *scoreLabel = [CCLabelBMFont labelWithString:[NSString stringWithFormat:@"Score : %d", score] fntFile:@"good_dog_plain_32.fnt"];
      scoreLabel.position = ccp(100, 300);
      [self addChild:scoreLabel z:1 tag:123];
   }
}

- (void)updateScore
{
   CCLabelBMFont *scorelabel = (CCLabelBMFont *)[self getChildByTag:123];
   [scorelabel setString:[NSString stringWithFormat:@"Score: %d",self.score]];
}

Upvotes: 1

Johnmph
Johnmph

Reputation: 3391

Use CCLabelAtlas instead and use setString to change the string of the CCLabelAtlas object.

Upvotes: 0

Related Questions