Pregunta

I can get the HUD layer to appear, but I can't seem to update it. I got it working in Ray's tutorial, but for some reason I can't get it working in my own app. I made a new Cocos2d project just so I can try and isolate the problem and I'm having the same issue... maybe you guys can help. ( I'm getting no errors and tried to fix the indentation as best I could for StackOverflow..)

Problem: I can't update the scoreLabel

Code:

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];
}
¿Fue útil?

Solución

The init is called when you invoke [HelloWorldLayer node] when the HUD is not created yet, ie, _hud is nil. Sending message to a nil object is a void operation and it doesn't crash as it is if calling functions on 'NULL` objects.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top