我正在我的游戏图层上创建一个HUD图层,添加一个标签,通过以下代码显示该HUD中的得分
// playGame Class
+(CCScene *) scene
{
// 'scene' is an autorelease object.
CCScene *scene = [CCScene node];
// 'layer' is an autorelease object.
playGameLayer *layer = [playGameLayer node];
// add layer as a child to scene
[scene addChild: layer];
// create HUD
id statsHuds = [HUDlayer statsHUDWithBackgroundSprite:HUDBackground withRect:CGRectMake(160,30, 130,60)];
[statsHuds addLabeltoStatsHUDwithName:@"Score" andValue:@"50"];
//[statsHuds setStatusString:@"yewq"];
//[statsHuds updateScorewithValue:199];
// add HUD
[scene addChild: statsHuds];
// return the scene
return scene;
}
- (id)init
{
// always call "super" init
// Apple recommends to re-assign "self" with the "super" return value
if( (self=[super init]))
{
[[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:NO];
[self performSelector:@selector(updateLabel) withObject:nil afterDelay:5];
}
return self;
}
-(void)updateScore
{
HUDlayer *obj = [[HUDlayer alloc]init];
[obj setScoreString:@"100"];
[obj release];
}
// HUDLayer Class
+(id)statsHUDWithBackgroundSprite:(NSString *)spriteName withRect:(CGRect)rect
{
HUDlayer *hud = [[HUDlayer alloc] init];
UIImage *image = [UIImage imageNamed:spriteName];
CCSprite *statsSprite = [CCSprite spriteWithCGImage:image.CGImage key:nil];
[statsSprite setPosition:ccp(rect.origin.x,rect.origin.y)];
[hud addChild:statsSprite];
return [hud autorelease];
}
-(void)addLabeltoStatsHUDwithName:(NSString *)labelName andValue:(NSString *)labelValue
{
[_statusLabel setString:@"no"];// [CCLabelBMFont labelWithString:@"no" fntFile:@"Arial.fnt"];
[_statusLabel setPosition:ccp(160,240)];
[self addChild:_statusLabel];
}
// label added above is not updating
- (void)setScoreString:(NSString *)string
{
_statusLabel.string = string;
NSLog(@"stats string after %@",_statusLabel.string);
}
_statuslbel一旦被添加到HUD就不会更新,即使NSlog返回新值 我可能做错了什么?
答案 0 :(得分:1)
在updateScore方法中,每次触发此方法时都会创建一个新的HUDLayer对象。
相反,您需要引用添加到场景中的HUDLayer。我建议你给你的HUDLayer一个标签:
[scene addChild: statsHuds z:0 tag:HUDTag];
然后在您的updateScore方法中,通过其标记访问该HudLayer并更新您的分数:
-(void)updateScore
{
HUDLayer * obj = (HudLayer *)[self.parent getChildByTag:HUDTag];
[obj setScoreString:@"100"];
}
希望这有帮助。