Cocos2d:从其他类访问子级

时间:2013-04-27 03:44:49

标签: objective-c cocos2d-iphone parent-child

确定!这是我初始化游戏时的主要场景,在ParallaxBgTestLayer中有一个类被添加为自称为DigBackground的自我的孩子,其中有property我要设置的另一层gameplayLayer

所以基本上我想从我的gameplay图层访问另一个班级中孩子的孩子。这样做的首选方式是什么?甚至可以使用标签访问其他类的孩子吗?

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

        ParallaxBgTestLayer *bgLayer = [ParallaxBgTestLayer node];
        [self addChild:bgLayer z:kParallaxBackgroundLayer];

        DigGameplayLayer *gameplayLayer = [DigGameplayLayer node];
        [self addChild:gameplayLayer z:kGameplayLayer];

    }
    return self;

2 个答案:

答案 0 :(得分:0)

你可以用非常简单的方式做到:

@class ParallaxBgTestLayer;
@class DigGameplayLayer;

@interface MainClass
{
    ParallaxBgTestLayer *bgTestLayer;
    DigGameplayLayer    *gameplayLayer;  
}
@property(monatomic, assign) ParallaxBgTestLayer bgTestLayer;
@property(monatomic, assign) DigGameplayLayer    *gameplayLayer;  
@end

@implementation MainClass

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

        self.bgLayer = [ParallaxBgTestLayer initWithParent:self];
        [self addChild:self.bgLayer z:kParallaxBackgroundLayer];

        self.gameplayLayer = [DigGameplayLayer initWithParent:self];
        [self addChild:self.gameplayLayer z:kGameplayLayer];

    }
    return self;

}
@end

@interface ParallaxBgTestLayer 
{
    CCNode *parentLayer;
}
@property(monatomic, assign) CCNode *parentLayer;

-(id) initWithParent:(CCNode*)inParent;
@end

@implementation ParallaxBgTestLayer

-(id) initWithParent:(CCNode*)inParent
{
   ParallaxBgTestLayer *obj = [ParallaxBgTestLayer node];
   obj.parentLayer = inParent;
   return obj;
}

-(void)CallMethodInGamePlayLayer
{
   [((DigGameplayLayer*)( (MainClass*)self. parentLayer).gameplayLayer  functionInGamePlayLayer];
}

@end


@interface DigGameplayLayer 
{
    CCNode *parentLayer;
}
@property(monatomic, assign) CCNode *parentLayer;

-(id) initWithParent:(CCNode*)inParent;

@implementation DigGameplayLayer

-(id) initWithParent:(CCNode*)inParent
{
   DigGameplayLayer *obj = [DigGameplayLayer node];
   obj.parentLayer = inParent;
   return obj;
}

-(void) functionInGamePlayLayer
{

}
@end

答案 1 :(得分:0)

我会通过使用以下步骤来完成它;

  • 更新/覆盖DigGameplayLayer的init方法,以获得一个参数ParallaxBgTestLayer
  • 例如,将您的游戏玩法初始化方法重命名为DigGameplayLayer initOnBackground:(ParallaxBgTestLayer *)backgroundLayer
  • 在DigGameplayLayer的实施文件中导入ParallaxBgTestLayer.h
  • 访问ParallaxBgTestLayer的任何局部变量(您添加到ParallaxBgTestLayer.h文件中的变量)

我认为如果您只需要从一个位置访问,这比创建单例对象更好。当我在我的应用程序中的多个位置需要它时,我使用单身。

我希望,这有助于......