我可以使HUD層出現,但我似乎無法更新它。我在Ray的教程中找到了它,但由於某種原因,我無法在自己的應用中使用它。我做了一個新的Cocos2d項目,以便我可以嘗試隔離問題,並且遇到同樣的問題......也許你們可以提供幫助。 (我沒有得到任何錯誤,並試圖修復縮進盡我所能爲StackOverflow的..)無法通過遊戲層調用HUD層方法Cocos2d
問題:我無法更新scoreLabel
代碼:
GameHUD.h
#import <Foundation/Foundation.h>
#import "cocos2d.h"
@interface GameHUD : CCLayer {
CCLabelTTF *scoreLabel;
}
- (void) updateScore:(int)score;
@end
GameHUD.m
#import "GameHUD.h"
@implementation GameHUD
- (id) init {
if (self = [super init]) {
scoreLabel = [CCLabelTTF labelWithString:@"00000" dimensions:CGSizeMake(240,100) hAlignment:kCCTextAlignmentRight fontName:@"Arial" fontSize:32.0f];
scoreLabel.anchorPoint = ccp(0,0);
scoreLabel.position = ccp(200,0);
scoreLabel.color = ccc3(255, 200, 100);
[self addChild:scoreLabel];
}
return self;
}
- (void)updateScore:(int)score {
scoreLabel.string = [NSString stringWithFormat:@"%i",score];
}
@end
HelloWorldLayer.h
#import "cocos2d.h"
#import "GameHUD.h"
@interface HelloWorldLayer : CCLayer
{
GameHUD *_hud;
}
@property (nonatomic,retain) GameHUD *hud;
+(CCScene *) scene;
@end
HelloWorldLayer.m
#import "HelloWorldLayer.h"
#import "AppDelegate.h"
#pragma mark - HelloWorldLayer
@implementation HelloWorldLayer
@synthesize hud = _hud;
+(CCScene *) scene
{
CCScene *scene = [CCScene node];
HelloWorldLayer *layer = [HelloWorldLayer node];
[scene addChild: layer];
GameHUD *hud = [GameHUD node];
[scene addChild:hud];
layer.hud = hud;
return scene;
}
-(id) init
{
if((self=[super init])) {
// create and initialize a Label
CCLabelTTF *label = [CCLabelTTF labelWithString:@"Layer A" fontName:@"Marker Felt" fontSize:64];
// ask director for the window size
CGSize size = [[CCDirector sharedDirector] winSize];
// position the label on the center of the screen
label.position = ccp(size.width /2 , size.height/2);
// add the label as a child to this Layer
[self addChild: label];
// Try to update the scoreLabel in the HUD (NOT WORKING)
[_hud updateScore:74021];
}
return self;
}
// on "dealloc" you need to release all your retained objects
- (void) dealloc
{
[super dealloc];
}
只有使用[tag:xcode]標籤才能瞭解關於IDE本身的問題。謝謝! – Undo 2013-04-22 20:44:29
好吧,想通了。無法從init方法更新hud,必須事後進行。調用更新方法從ccTouchBegan可以正常工作。我猜hud對象還沒有創建?如果是這樣,我想知道爲什麼我沒有得到一個不良訪問錯誤。奇怪。 – mike 2013-04-22 21:57:26
只有在訪問釋放對象時纔會出現此錯誤。在創建之前,objective-c中的所有對象都具有值「nil」,而不是「NULL」,因爲它在C++中。主要區別是你可以發送任何消息到'nil'而不會導致錯誤。 – Morion 2013-04-23 06:16:25