My AppDelegate makes the following call to start my game scene:
[[CCDirector sharedDirector] replaceScene: [HelloWorld sceneWithResponseDelegate:self]];
When the scene is finished it adds a MenuLayer (which is a singleton):
MenuLayer *menu = [MenuLayer layerWithLevel:@"forest" score:score responseDelegate:mainMenu];
[[[CCDirector sharedDirector] runningScene] addChild:menu];
The function that is called:
+ (id) layerWithLevel:(NSString *)level score:(int)score responseDelegate:(id)rd {
static MenuLayer *_singleton;
if (_singleton == nil) {
_singleton = [[MenuLayer alloc] initWithLevel:level score:score];
_singleton.delegate = rd;
}
else {
[_singleton reuseWithLevel:level score:score];
_singleton.delegate = rd;
}
return _singleton;
}
Upon clicking a button, it can restart the same game scene:
- (void)ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
UITouch *touch = [touches anyObject];
CGPoint location = [touch locationInView:[touch view]];
location = [[CCDirector sharedDirector] convertToGL:location];
NSString *button = [Button checkButtonPressed:location action:TouchesBegan buttons:_buttons];
if (button == @"play") {
[[SimpleAudioEngine sharedEngine] stopBackgroundMusic];
[delegate menuResult:_level];
}
else if (button == @"menu") {
[[SimpleAudioEngine sharedEngine] stopBackgroundMusic];
[delegate menuResult:button];
}
}
However after clicking the button the app crashes with an EXC_BAD_ACCESS.
Is this the right way to be switching scenes in cocos2d?
The menuResult function actually does the following:
- (void) menuResult: (NSString *)result {
if (result == @"forest") {
[[CCDirector sharedDirector] replaceScene: [HelloWorld sceneWithResponseDelegate:self]];
}
if (result == @"hills") {
[[CCDirector sharedDirector] replaceScene: [HillsScene sceneWithResponseDelegate:self]];
}
if (result == @"menu") {
[[CCDirector sharedDirector] replaceScene: [Menu sceneWithResponseDelegate:self]];
}
}
So this would actually replace the scene that holds the MenuLayer that's calling this method. So the HelloWorld scene may be replaced by itself, or by the MenuScene (main menu).
This works from HillsScene, but doesn't work from HelloWorld - I've double checked the code and it's exactly the same.
So can a layer in a scene call a function which effectively kills the scene? Can anyone tell me what I'm doing wrong here?
Thanks.