简体   繁体   中英

How do I properly pause in SpriteKit when the application goes to background?

Ok, I know that SpriteKit automatically pauses and resumes games when the enter foregrounds and backgrounds, but I want to go to the pause menu (which is a method in my GameScene) whenever the application goes to the background. I do this by calling that method in -applicationDidEnterBackground , but for some reason the game crashes. What is the proper way to do this?

EDIT:

This is the error message:

Terminating app due to uncaught exception 'Attemped to add nil node', reason: 'Attemped to add nil node to parent: <SKScene> name:'(null)' frame:{{0, 0}, {1, 1}}'
*** First throw call stack:
(0x181d2259c 0x1924780e4 0x181d224dc 0x18635812c 0x10003dd90 0x10003e818 0x1000394b0 0x1867627c0 0x18676acbc 0x18676ac44 0x18675e578 0x189f9162c 0x181cdaa28 0x181cd9b30 0x181cd7d30 0x181c050a4 0x18ada75a4 0x18653a3c0 0x10003f700 0x192ae6a08)
libc++abi.dylib: terminating with uncaught exception of type NSException
(lldb)

This is what the pauseGame method does:

NSLog(@"Pausing...");
[self removeActionForKey:@"spawn"];
[self addChild:self.pausedImage];
[self addChild:self.restart];
[self addChild:self.resume];

NSString *path = [NSString stringWithFormat:@"%@/menu.mp3", [[NSBundle mainBundle]resourcePath]];
NSURL *pauseMusicURL = [NSURL fileURLWithPath:path];
self.pauseMusicPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:pauseMusicURL error:nil];
self.pauseMusicPlayer.numberOfLoops = -1;
[self.pauseMusicPlayer play];

[self.pause removeFromParent];
self.scoreLabelInGame.position = CGPointMake(self.restart.position.x, self.resume.position.y - self.customUnit);
self.actualScore.position = CGPointMake(self.restart.position.x, self.scoreLabelInGame.position.y - self.customUnit);
self.isPaused = YES;
[self.mainMusicPlayer pause];
} 

This basically stops every process in the game (Everything only works if isPaused = NO) And it simulates a pause menu on top of the game.

I assume that

  1. you are populating self.pausedImage , self.restart , self.resume
  2. at least 1 of the 3 properties above is erroneously nil

Now if my assumptions are correct (can you confirm?), I think one of the following scenarios can be the cause of the crash:

  1. at least 1 of the 3 properties mentioned above are declared as weak
  2. the code that populates these 3 properties has never been called when you pause the game
  3. you have some code that set to nil at least 1 of the 3 properties

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM