Search code examples
objective-ccocos2d-iphoneccsprite

Error when using Multiple Sprite Sheets in Game Layer with Cocos2d


I have the following code:

[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"cow_sprite.plist"];
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"ray_sprite.plist"];
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"chicken_sprite.plist"];
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"tank_sprite.plist"];
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:@"human_sprite.plist"];

self.raySpriteSheet = [CCSpriteBatchNode batchNodeWithFile:@"ray_sprite.png"];
self.tankSpriteSheet = [CCSpriteBatchNode batchNodeWithFile:@"tank_sprite.png"];
self.chickenSpriteSheet = [CCSpriteBatchNode batchNodeWithFile:@"chicken_sprite.png"];
self.cowSpriteSheet = [CCSpriteBatchNode batchNodeWithFile:@"cow_sprite.png"];
self.humanSpriteSheet = [CCSpriteBatchNode batchNodeWithFile:@"human_sprite.png"];

[self addChild:self.raySpriteSheet];
[self addChild:self.tankSpriteSheet];
[self addChild:self.chickenSpriteSheet];
[self addChild:self.cowSpriteSheet];
[self addChild:self.humanSpriteSheet];

for (int i = 0; i < 13; ++i) {
    Dice* d = [[Dice alloc] initRandom];

    if (d.fileNum == 0 || d.fileNum == 1) {
        [self.raySpriteSheet addChild:d.sprite];
    }else if(d.fileNum == 2){
        [self.tankSpriteSheet addChild:d.sprite];
    }else if(d.fileNum == 3){
        [self.chickenSpriteSheet addChild:d.sprite];
    }else if(d.fileNum == 4){
        [self.cowSpriteSheet addChild:d.sprite];
    }else if(d.fileNum == 5){
        [self.humanSpriteSheet addChild:d.sprite];
    }
    [rollDiceArray addObject:d];
}

The idea is that I want to be able to use 5 separate sprite sheets for 5 separate dice animations. I am predetermining a value for each die, then assigning a sprite/animation, and finally adding that sprite to the appropriate CCSpriteBatchNode.

It will make it through the first iteration but then errors on the second, giving this error:

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'CCSprite is not using the same texture id'

Any thoughts?


Solution

  • The error indicates that you were trying to add a CCSprite to a CCSpriteBatchNode which was initialized with a different texture than the texture the CCSprite is using. In other words: CCSpriteBatchNode and all CCSprite added to that batch node must use the same texture.

    As a side note: if the cow, ray, tank, chicken and human images all fit into one texture atlas, then by all means put them into one texture atlas. The point of a texture atlas is not to sort and categorize your images but to speed up rendering them. The more images you can pack into the same texture atlas, the faster you can render them - ideally with just one sprite batch node.