我是Cocos2d的初学者,所以虽然这里有一些代码。有经验的人应该能够看到我在这里做错了什么。当我尝试在NSAssert
类方法中获取作为子级添加到此图层的backgroundLayer
实例时,它会在GameBackground class
中的+(id)scene
崩溃。崩溃导致它Nil
(
GameBackground
类。但是当我要求+(id)scene
时,我想我用node
方法初始化了它?但请纠正我,我的想法在这个问题上很模糊。
static GameLayer *sharedGameLayer = nil;
+(id) scene
{
CCScene *scene = [CCScene node];
//GameLayer* layer = [GameLayer node];
//[scene addChild:layer];
CCNode *backgroundLayer = [GameBackground node];
[scene addChild:backgroundLayer z:1 tag:LayerTagBackgroundLayer];
CCLayer *cocosObjectsLayer = [HelloWorldLayer node];
[scene addChild:cocosObjectsLayer z:2 tag:LayerTagGameLayer];
CCLayer *userTouchInterface = [GameUserTouchInteface node];
[scene addChild:userTouchInterface z:3 tag:LayerTagUILayer];
return scene;
}
// To access this scene: MultiLayerScene* sceneLayer = [MultiLayerScene sharedLayer];
+ (GameLayer *) sharedLayer
{
NSAssert(sharedGameLayer = nil, @"sharedGameLayer not available.");
//if (sharedGameLayer == nil) sharedGameLayer = [[GameLayer alloc] init];
return sharedGameLayer;
}
-(id) init
{
NSLog(@"init called");
self = [super init];
if (self)
{
NSAssert(sharedGameLayer == nil, @"another GameLayer is already in use!");
sharedGameLayer = self;
// uncomment if you want the update method to be executed every frame
//[self scheduleUpdate];
}
return self;
}
// MultiLayerScene* sceneLayer = [MultiLayerScene sharedLayer];
// To access this scene: GameBackgroundLayer* backgroundLayer = [sceneLayer backgroundLayer];
-(GameBackground *) backgroundLayer
{
CCNode *layer = [self getChildByTag:LayerTagBackgroundLayer];
NSAssert([layer isKindOfClass:[GameBackground class]], @"%@: not a BackgroundLayer!", NSStringFromSelector(_cmd));
return (GameBackground *)layer;
}
然后尝试从另一个类获取背景图层的实例:
GameBackground *backgroundLayer = [GameLayer sharedLayer].backgroundLayer;
[backgroundLayer runAction:sequence];
答案 0 :(得分:1)
我猜测失败的断言是.-
NSAssert(sharedGameLayer = nil, @"sharedGameLayer not available.");
您将nil
分配给sharedGameLayer
而不是比较(==
)。另外,您已经注释了设置sharedGameLayer
的行。只是在这里猜测,但你可能想做这样的事情.-
+(id) scene
{
CCScene *scene = [CCScene node];
sharedGameLayer = [GameLayer node];
[scene addChild:layer];
return scene;
}
让static
构造函数尽可能干净。
+ (GameLayer *) sharedLayer
{
return sharedGameLayer;
}
-(id) init
{
NSLog(@"init called");
self = [super init];
if (self)
{
CCNode *backgroundLayer = [GameBackground node];
[self addChild:backgroundLayer z:1 tag:LayerTagBackgroundLayer];
CCLayer *cocosObjectsLayer = [HelloWorldLayer node];
[self addChild:cocosObjectsLayer z:2 tag:LayerTagGameLayer];
CCLayer *userTouchInterface = [GameUserTouchInteface node];
[self addChild:userTouchInterface z:3 tag:LayerTagUILayer];
// uncomment if you want the update method to be executed every frame
//[self scheduleUpdate];
}
return self;
}
在init
方法中创建节点树,并将它们添加为根层(sharedGameLayer
)的子节点而不是场景对象。