Question

When I hit the retry button in my game, I want it to reload the MainScene. I am doing this with:

-(void)retry
{
    SKTransition *transition = [SKTransition fadeWithDuration:.4];
    MainScene *gameOver = [[MainScene alloc] initWithSize:self.size];
    [gameOver didMoveToView:self.view];
    [self.scene.view presentScene:gameOver transition:transition];
}

However, this is causing the memory/CPU usage to increase (by a lot) each time I hit retry. After about 10-20 retries, there is a noticeable lag.

I made all my SKEmitterNode and SKSpriteNode static and that fixed the memory problem, so I suspect that my sprites, emitters, etc are not being released from the memory and are being re-loaded every time I hit retry, doubling it.

I am loading the sprites/emitters like this:

@implementation MainScene {
    SKEmitterNode *_bubbleEmitter;
    SKSpriteNode *_sunglasses;
    ...
}

- (id)initWithSize:(CGSize)size
{
  if (self = [super initWithSize:size]) 
  {
     _sunglasses = [SKSpriteNode spriteNodeWithImageNamed:@"sunglasses"];
     [_sunglasses setPosition:CGPointMake(self.size.width/2,  self.size.height + 10)];
     [self addChild:_sunglasses];

     ...
  }
  return self;
}

Am I loading the sprites or the retry wrong?

Was it helpful?

Solution

This may or may not be the cause, but it's certainly wrong to call this method yourself:

[gameOver didMoveToView:self.view];

The didMoveToView: method is sent to the scene by the SKView when you present the scene. That means this method will actually run twice.

Also verify that your scenes are deallocating properly by implementing:

-(void) dealloc
{
    NSLog(@"dealloc: %@", self);
}

Watch for the log or set a breakpoint to confirm the scene deallocates. If it isn't, check for memory leaks and retain cycles.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top