I have created a number of CCSprites using spriteWithFile.
How do I change the image for the sprite during runtime?
I need to change a few sprites images qui
if You are using SpriteSheets then this will work
CCSpriteBatchNode *batch;
[[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFrameWithFile:@"file.plist"];
batch = [[[CCSpriteBatchNode alloc] initWithFile:@"file.png"] capacity:50] autorelease];
[self addChild:batch];
you need to make one cctexture2d object in such a way
CCTexture2D* newtexture = [[CCTextureCache sharedTextureCache] addImage:@"new-texture"]; [mainSprite setTexture: newtexture];
this is a whole thing needed to be done if you want change sprite image texture run time.
In COCOS2D-X you can do this by following way
CCTexture2D *tex = CCTextureCache::sharedTextureCache()->addImage("xyz.png");
sprit_name->setTexture(tex);
iF YOU WANT TO CHANGE THE SPRITE SIZE THEN ALSO WRITE THIS LINE
sprit_name->setTextureRect(CCRectMake(0,0, tex->getContentSize().width, tex->getContentSize().height));
For those who are using Cocos2d-iPhone v 3.0.0 or later
demonSprite.texture = [[CCSprite spriteWithImageNamed:@"steelDemonNormal.png"] texture];
if you want to change the images continuously then write following code in your init method
CCTexture2D *tex1 = [[CCTextureCache sharedTextureCache] addImage:@"image1.png"];
CCTexture2D *tex2 = [[CCTextureCache sharedTextureCache] addImage:@"image2.png"];
CCTexture2D *tex3 = [[CCTextureCache sharedTextureCache] addImage:@"image3.png"];
CCSprite *sprite = [CCSprite spriteWithTexture:tex1];
//Make above variables as class level to access in whole class
[self addChild:sprite];
//position the sprite according to your need
write this line where you want to change the image
[sprite setTexture:tex3];