2010-12-03 76 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對象。

希望有所幫助。