Cocos2d V3 iOS - How to access runningScene from App Delegate

故事扮演 提交于 2019-12-13 02:47:22

问题


I’m wanting to access my running scene in the App Delegate. The problem is, [[CCDirector sharedDirector] runningScene] returns a CCScene object, rather than the actual class of my scene MyMainScene. If I try to call any of my custom methods, I get:

-[CCScene customMethod]: unrecognized selector sent to instance 0x156bedc0

I’ve tried casting like this

CCScene *scene = [[CCDirector sharedDirector] runningScene];
MyMainScene *mainScene = (MyMainScene*)scene;
[mainScene customMethod];

But this has no effect. The mainScene object above still returns a class name of CCScene, and will crash at runtime.

I’ve also tried dynamic casting, as suggested here Objective-C dynamic_cast?. With dynamic casting I don’t get a crash, but the method always returns null.


UPDATE - MORE CODE

AppController implementation

#import "cocos2d.h"
#import "AppDelegate.h"
#import “ IDFAMainScene.h”

@implementation AppController

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{

    // default code here
}

- (CCScene*) startScene {
    return [CCBReader loadAsScene:@“IDFAMainScene”];
}

- (void)applicationDidBecomeActive:(UIApplication *)application {

    CCScene *scene = [[CCDirector sharedDirector] runningScene];
    IDFAMainScene *mainScene = (IDFAMainScene*)scene;
    [mainScene customMethod];

}

IDFAMainScene header

#import <Foundation/Foundation.h>
#import "cocos2d.h"
@interface IDFAMainScene : CCNode {

}

-(void)customMethod;

IDFAMainScene implementation

#import "IDFAMainScene.h"

@implementation IDFAMainScene

-(void)didLoadFromCCB{
    [self customMethod];
}

-(void)customMethod{
    NSLog(@“custom method called");
}

The above application will compile. It loads the IDFAMainScene file okay as customMethod gets called and logs "custom method called" from didLoadFromCCB, but when it then tries to call the customMethd from the cast object in applicationDidBecomeActive... it crashes with error

-[CCScene customMethod]: unrecognized selector sent to instance 0x175b7e50

回答1:


The loadAsScene method returns a CCScene object with your custom class as its only child. Hence you need to change this code to get your custom class as follows (I also converted to dot notation as I like to propagate it whenever possible):

CCScene *scene = [CCDirector sharedDirector].runningScene;
IDFAMainScene *mainScene = (IDFAMainScene*)scene.children.firstObject;
[mainScene customMethod];


来源:https://stackoverflow.com/questions/24759662/cocos2d-v3-ios-how-to-access-runningscene-from-app-delegate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!