0

好的!这是我初始化游戏的主要场景,其中有一个ParallaxBgTestLayer作为 self 的子类添加的类,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;
4

2 回答 2

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
于 2013-04-27T17:15:02.987 回答
0

我将通过以下步骤来做到这一点;

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

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

我希望这有帮助...

于 2013-05-01T23:41:42.453 回答