Search code examples
iosobjective-csprite-kitnsstringsklabelnode

App freezes after second point, Objective C


I want to make small game like 'Ping Pong'. Everything was working fine, but now, when I want to add a score, the game freezes. I used this code for another project of mine and everything was fine.

Here is the code for the score part :

-(void)scoreCount{
    score ++;
    if(scoreLabel == nil){

        scoreLabel = [SKLabelNode labelNodeWithFontNamed:@"ROTORcapExtendedBold"];
        scoreLabel.fontSize = 40;
        scoreLabel.position = CGPointMake(self.frame.size.width/2,self.frame.size.height/3);
        scoreLabel.zPosition = 0;
    }
    [self addChild:scoreLabel];
    scoreLabel.text = [NSString stringWithFormat:@"%ld",(long)score];
}

in console I got this message:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attemped to add a SKNode which already has a parent: name:'(null)' text:'1' fontName:'ROTORcapExtendedBold' position:{189.33333, 106.66666}'

After I remove the line scoreLabel == nil, the app doesn't freeze, but then the score on the screen copies an old score and makes the score unreadable.

How can I fix it?


Solution

  • Put the [self addChild:scoreLabel] inside the if statement.

    Currently you are trying to add it to the scene every time you update the label and you can't add it again once it's already in the scene.