所以我的 Cocos2d 游戏出了点问题。我最近添加了一些代码,可以让我在游戏中某些关卡的开头出现对话消息。每当我重新启动将对话框 cclayer 添加到当前场景的关卡的关卡(替换场景)时,我都会通过 iPhone 模拟器收到 BAD ACCESS 错误,然后如果我在 iPhone 4S 上运行它,我收到一个 SIGARBT 错误,上面写着
“ *由于未捕获的异常‘NSInternalInconsistencyException’而终止应用程序,原因:‘已添加子项。无法再次添加’”
这是我制作的第一个 cocos2d 游戏。我玩弄了很多 cocos2d 并且有了我认为是基本的理解。我有很多其他语言的编程经验,但大约 3 个月前我才开始学习 Objective-c。
这是我的代码。
游戏对话.h
#import <Foundation/Foundation.h>
#import "cocos2d.h"
#import "GameData.h"
@interface GameDialogLayer : CCLayer {
NSString *dialogText;
}
@property (nonatomic, retain) NSString *dialogText;
+(CCScene *) scene;
-(void) addDialogWithText: (NSString *)text;
@end
游戏对话.m
#import "GameDialogLayer.h"
@implementation GameDialogLayer
@synthesize dialogText;
+(CCScene *) scene
{
CCScene *scene = [CCScene node];
GameDialogLayer *layer = [GameDialogLayer node];
[scene addChild: layer];
return scene;
}
-(id) init
{
if( (self=[super init]) ) {
// init the bg overlay
CCLayerColor *backgroundLayer = [CCLayerColor layerWithColor:ccc4(0, 0, 0, 175)];
[self addChild:backgroundLayer z:0];
// init the dialog box
CCSprite *dialogBox = [CCSprite spriteWithFile:@"dialog.png"];
dialogBox.position = ccp([[CCDirector sharedDirector] winSize].width / 2, [[CCDirector sharedDirector] winSize].height / 2);
[self addChild:dialogBox];
// init the dialog menu
CCMenuItemImage *dialogOkay = [CCMenuItemImage itemWithNormalImage:@"dialogOkayButton.png" selectedImage:@"dialogOkayButtonPressed.png" target:self selector:@selector(okayButton)];
CCMenu *dialogMenu = [CCMenu menuWithItems:dialogOkay, nil];
dialogMenu.position = ccp(dialogMenu.position.x, dialogMenu.position.y - 118);
[self addChild:dialogMenu];
}
return self;
}
-(void) okayButton
{
[GameData sharedGameData].isPaused = 0;
[[self parent] schedule:@selector(startCountdown:) interval:1];
[[self parent] removeChild:self cleanup:YES];
}
-(void) addDialogWithText: (NSString *)text
{
CCLabelTTF *dialogTextLabel = [CCLabelTTF labelWithString:text dimensions:CGSizeMake(180, 250) hAlignment:kCCTextAlignmentLeft fontName:@"MarkerFelt-Thin" fontSize:20];
dialogTextLabel.color = ccBLACK;
dialogTextLabel.position = ccp([[CCDirector sharedDirector] winSize].width / 2, [[CCDirector sharedDirector] winSize].height / 2);
[self addChild:dialogTextLabel];
}
- (void) dealloc
{
[super dealloc];
}
@end
然后对话框被添加到我的 levelData 类中的对话框属性中,该类为每个级别进行实例化并保存级别的属性。
这是持有它的财产
@property (nonatomic, retain) GameDialogLayer *dialog;
这就是我如何将对话框添加到 levelData 对话框属性
-(void) addDialog: (NSString *)dialogText
{
dialog = [GameDialogLayer node];
[dialog addDialogWithText:dialogText];
}