cocos2d-iphoneccspritebatchnode

adding a normal CCSprite to CCSpriteBatchNode crashes


I am getting this exception in logs

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

What I am trying to do is adding a normal "myfile.png" file to a SpriteBatchNode

**declaration of batch node

CCSpriteBatchNode *_backgroundLayer = [CCSpriteBatchNode batchNodeWithFile:@"sprites.png"];

** usage

This line works perfect

CCSprite *sprite1 = [CCSprite spriteWithSpriteFrameName:@"PngFileKeptInSpriteSheet.png"];
[_backgroundLayer addChild:sprite1];

But, when I use a direct *.png file to add to batch node, It crashes

    CCSprite *sprite2 = [CCSprite spriteWithFile:@"myfile.png"];

crashes on line

        [_backgroundLayer addChild:sprite2];

On further debugging I found that:

The assertion failure is in file CCSpriteBatchNode.m

inside method -(void) addChild:(CCSprite*)child z:(NSInteger)z tag:(NSInteger) aTag

at line NSAssert( child.texture.name == textureAtlas_.texture.name, @"CCSprite is not using the same texture id");

P.S. : by "normal" I mean not taken from *.plist file


Solution

  • First and foremost, I'd update cocos2D. However, that isn't your problem and probably isn't "fixed" in the latest version anyway. This isn't really a bug

    Batch nodes require that all the sprites that you intend to batch are using the same texture. When you load a sprite sheet, it uses one, large texture. When you call spriteWithFile, cocos2d creates a texture from that image.

    It's rare that you'll want to create a batch node from a sprite using spriteWithFile. The only scenario I can think of is when you want to draw the same image many times. (Rather than many images from the same texture).

    In short, what you are trying to do is unsupported and doesn't make much sense anyway as the two sprites wouldn't be batchable.