Mord Fustang Mord Fustang - 3 months ago 10
Objective-C Question

How to update gamehud in a CCSprite or CCNode, Cocos2d

I have a

Gamehud
where I want to display an object's name. There are lots of objects/sprites in main scene what I am trying to do is to display selected(on touch) objects' name on
Gamehud
.

Problem is if I alloc
Gamehud
in
CCsprite
class it creates new instance and does not update current
Gamehud
. If I use something like
GameHUD *gamehud= (GameHUD *)[self.parent getChildByTag:99];
nothing happens I cannot send the object to GameHud class.

So what would be the correct way to update game hud in a
ccsprite or ccnode
class?

Main Scene;

-(id) init
{
if ((self = [super init]))
{
gameHud = [GameHUD gamehud];
[self addChild:gameHud z:2 tag:99];
}
}


My GameHud

+(id) gamehud
{
return [[self alloc] init];
}

-(id) init
{
if ((self = [super init]))
{
//bunch of labels
}
}


-(void)showName: :(Object *)obj
{
NSLog(@"Object name is %@", obj.name);
[_labelSpeed setString:obj.name];
}


In Object Class:CCSprite

-(void) onTouch
{
//obj is the object with name property that I want to use
GameHUD *gamehud= (GameHUD *)[self.parent getChildByTag:99]; // does not send the obj to gamehud and showName is not called
//GameHud *gamehud= [GameHud alloc] init]; // this displays nslog but doesnt update _label
[gamehud showName:obj];
}

Answer

You may need to create a singleton or something like a semi singleton. Just add new nsobject class name "SingletonGameHud" to your app

SingletonGameHud.h

#import <Foundation/Foundation.h>
#import "GameHUD.h"

//create singleton class to use gamehud in movingobject class
@interface SingletonGameHud : NSObject
{
    GameHUD *gamingHud;

}

@property(nonatomic,strong) GameHUD *gamingHud;

+(SingletonGameHud *)sharedInstance;


@end

SingletonGameHud.m

#import "SingletonGameHud.h"
#import "GameHUD.h"

@implementation SingletonGameHud

@synthesize gamingHud=_gamingHud;


+ (SingletonGameHud *)sharedInstance
{
    static SingletonGameHud *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[SingletonGameHud alloc] init];
        // Do any other initialisation stuff here
    });
    return sharedInstance;
}

- (id)init {
    if (self = [super init]) {
        _gamingHud = [GameHUD hud];

    }
    return self;
}

@end

in your game scene call

SingletonGameHud *sharedInstance= [SingletonGameHud sharedInstance];
hud = sharedInstance.gamingHud;
[self addChild:hud z:2 tag:99];

in your on touch method call

-(void) onTouch
{
    SingletonGameHud *sharedInstance= [SingletonGameHud sharedInstance];
    [sharedInstance.gamingHud showName:obj];

}