【问题标题】:Cocos2d V3 iOS - How to access runningScene from App DelegateCocos2d V3 iOS - 如何从 App Delegate 访问 runningScene
【发布时间】:2014-07-16 00:21:20
【问题描述】:

我想在 App Delegate 中访问我正在运行的场景。问题是,[[CCDirector sharedDirector] runningScene] 返回一个CCScene 对象,而不是我的场景MyMainScene 的实际类。如果我尝试调用我的任何自定义方法,我会得到:

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

我试过这样投射

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

但这没有任何效果。上面的mainScene对象仍然返回一个类名CCScene,运行时会崩溃。

我也尝试过动态投射,这里建议 Objective-C dynamic_cast?。使用动态转换,我不会崩溃,但该方法总是返回 null。


更新 - 更多代码

AppController 实现

#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 标头

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

}

-(void)customMethod;

IDFAMainScene 实现

#import "IDFAMainScene.h"

@implementation IDFAMainScene

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

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

上面的应用程序将被编译。它可以加载 IDFAMainScene 文件,因为 customMethod 被调用并从 didLoadFromCCB 记录 "custom method called",但是当它尝试从 applicationDidBecomeActive... 中的演员对象调用 customMethd 时,它会因错误而崩溃

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

【问题讨论】:

  • 你的代码应该可以工作,AFAIK。如果您需要我们的帮助,我认为您将不得不显示更多代码。

标签: ios objective-c cocos2d-iphone


【解决方案1】:

loadAsScene 方法返回一个 CCScene 对象,其中您的自定义类作为其唯一的子对象。因此,您需要更改此代码以获取您的自定义类,如下所示(我也转换为点表示法,因为我喜欢尽可能传播它):

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多