2010-12-03 73 views
0

在cocos2d-iphone我有一个名为GameScene在Objective-C初始化一个对象,并给它一个实例名称

我想,但是我不知道的实例的名称使用这个类从另一个类CCLayer类GameScene类

我如下

-(id) init { 
     if ((self = [super init])) { 

但是这不会给我的实例的名称初始化GameScene类的一个实例

我的文档阅读,可以使用一种叫做initWithName方法,所以我想是这样的,但它不工作,它给了我警告:

 In function '-[GameScene init]': 
     warning: 'CCLayer' may not respond to '-initWithName:' 

我试过的代码是

-(id) init { 
     if ((self = [super initWithName:"gamescene"])) { 

我会通过游戏只需要这个类的一个实例,但我不能捕获该实例的处理程序,所以我可以从其他类使用它?

任何想法

非常感谢


更新:

你好

我要更新代码,让你知道,我想你的解决方案,但它似乎还没有工作

在MyAppDelegate.h我的代码此行:

首先,我已经定义了应用程序委托到与其它类

MyAppDelegate.h

#define AD (MyAppDelegate *)[[UIApplication sharedApplication] delegate] 

并在MyAppDelegate分享。米我有以下代码:

gs = [[GameScene alloc] init];//this is the gamescene 
sc = [gs scene]; //this calls the method -(id)(scene) 
[[CCDirector sharedDirector] runWithScene: sc]; //runwithscene 
现在

当我试图使用其他类 - 例如player.m类 -

内的GS

player.m

GameScene* gs = [AD gs]; //retrieving the instance from appdelegate 
[gs updateScoreByAmount:5];/calling the method "updateScoreByAmount" 

的结果,你猜会发生什么?

程序运行没有出错但是GS实例似乎比通过,因为这种方法“updateScoreByAmount”中的appdelegate运行,不影响现场的其中一个由runWithScene中的appdelegate

任何想法运行不同?

许多感谢所有那些谁试图帮助

+0

这是一个非常令人困惑的问题。对象本身并不具有名称。很难确定你正在做什么,以及你在做什么样的麻烦。 – Ryan 2010-12-03 03:00:45

+0

尝试`if((self = [super initWithName:@“gamescene”]))` – vikingosegundo 2010-12-03 03:16:38

+0

@Ryan,我只想从另一个类访问gamescene类的方法吗? – ahmed 2010-12-03 04:05:23

回答

0

如果我理解正确,你需要GameScene类的实例的引用?如果是这样的话,它取决于如何创建对象。你可能正在创建一些控制器类的实例,它看起来是这样的:

GameScene *gameScene = [[GameScene alloc] init]; 

这里,gameScene会参考你所需要的实例。

0

艾哈迈德

代替存储的一个指针顶级的场景,你可以做到这一点得到它的访问:

GameScene* myScene = (GameScene*)[[CCDirector sharedDirector] runningScene]; 

CCDirector是一个单身,而且它知道它是什么样的场景目前运行,所以你不需要保留一个指针,你可以在需要时使用上面的方法。

因为GameScene是CCScene的孩子,您的运行场景将是您的GameScene对象。

希望有所帮助。