Sprite kit 尝试添加子项时出现“NSInvalidArgumentException”

Sprite kit 尝试添加子项时出现“NSInvalidArgumentException”,sprite-kit,Sprite Kit,我运行代码时出错。误差为 由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:'尝试添加已具有父级的SKNode:名称:'null'纹理:['Topobsticate1' 我搜索了有关问题的内容,但找不到任何解决方案。我知道发生错误的行。[self addChild:topobstacks[y]]是问题的根源。这是我的代码 - (void)createObstacles { // Calculate how many obstacles we n

我运行代码时出错。误差为

由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:'尝试添加已具有父级的SKNode:名称:'null'纹理:['Topobsticate1'

我搜索了有关问题的内容,但找不到任何解决方案。我知道发生错误的行。[self addChild:topobstacks[y]]是问题的根源。这是我的代码

- (void)createObstacles
{
    // Calculate how many obstacles we need, the less the better
    nbObstacles = ceil(WIDTH(self)/(OBSTACLE_INTERVAL_SPACE));

    CGFloat lastBlockPos = 0;
    bottomObstacles = @[].mutableCopy;
    topObstacles = @[].mutableCopy;

    SKSpriteNode * topObstacle1 = [SKSpriteNode   spriteNodeWithImageNamed:@"topObstacle1"];
[topObstacles addObject:topObstacle1];

SKSpriteNode * topObstacle2 = [SKSpriteNode spriteNodeWithImageNamed:@"topObstacle2"];
[topObstacles addObject:topObstacle2];

SKSpriteNode * bottomObstacle1 = [SKSpriteNode spriteNodeWithImageNamed:@"bottomObstacle1"];
[bottomObstacles addObject:bottomObstacle1];

SKSpriteNode * bottomObstacle2 = [SKSpriteNode spriteNodeWithImageNamed:@"bottomObstacle2"];
[bottomObstacles addObject:bottomObstacle2];


for (int i=0;i<nbObstacles;i++) {

    int y = arc4random() % 2;
    [topObstacles[y] setAnchorPoint:CGPointZero];

    [self addChild:topObstacles[y]];

    int z = arc4random() % 2;
    [bottomObstacles[z] setAnchorPoint:CGPointZero];

    [self addChild:bottomObstacles[z]];

    }

那么,您对此有何看法?

在for循环中选择一个随机数组索引,其中可以再次随机选择相同的索引y,从而添加相同的对象,例如索引1处的对象两次:

// 1st iteration, y is 1:
int y = arc4random() % 2;
[self addChild:topObstacles[y]];

// 2nd iteration, y is randomly chosen to be 1 again:
int y = arc4random() % 2;
[self addChild:topObstacles[y]]; // BAM! This node has already been added...

若要修复此问题,请选择另一个随机数,如果Topobstacks[y]。parent不是nil,或者仅从数组中删除使用[Topobstacks removeObjectAtIndex:y]添加的节点-这要求Topobstacks必须是NSMutableArray。

您要向同一个父节点添加两次节点。您的确切意思是什么,我该如何解决?感谢您的回复,我终于明白我在哪里添加了两次节点。但是如果我想添加两次相同的节点,我该怎么办?我想生成随机障碍,有时相同的障碍可能会出现连续生成。创建具有相同纹理的新精灵/properties@user3235456-如果Cocos的回答解决了你的问题,你应该接受。