麻烦从游戏层Cocos2d调用HUD层方法

时间:2013-04-22 20:38:05

标签: ios cocos2d-iphone hud

我可以让HUD图层出现,但我似乎无法更新它。我在Ray的教程中使用它,但出于某种原因,我无法在我自己的应用程序中使用它。我做了一个新的Cocos2d项目,所以我可以尝试找出问题并且我遇到同样的问题...也许你们可以提供帮助。 (我没有收到任何错误,并试图尽可能地为StackOverflow修复缩进..)

问题:我无法更新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];
}

1 个答案:

答案 0 :(得分:1)

当您尚未创建HUD时调用init时调用[HelloWorldLayer node],即_hudnil。向nil对象发送消息是一个无效操作,如果在'NULL`对象上调用函数,它就不会崩溃。