Search code examples
iphonecocos2d-iphonensmutablearrayccsprite

CCSprites in NSMutableArray does not reappear after scene change


I am making a game and i am putting CCSprites in a NSMutableArray.

When i start the game for the first time the sprites are appearing on screen, everything seems to work fine. But when i change to another scene and come back, none of the sprites are visible on screen. Here below is the code to initialize the Sprites.

-(void spritesInit)
    gpsUsersSpritesArray        = [[NSMutableArray alloc]init];
   for (int i = 0 ; i < [userArray count] ; i++){
      playerSprite = [CCSprite spriteWithFile:@"greenspot.png"];
      playerSprite.position = ccp( winSize.width/2, winSize.height/2);
      [self addChild:playerSprite z:5];
      [gpsUsersSpritesArray addObject:playerSprite];
      [playerSprite release];
   }
}

The above method is run every time the scene is called.

I run the action below on the sprites, that works also fine the first time, but again not when i leave and return to the scene. The sprites seems to be loaded and the code itterates through the NSMutableArray in question without a crash, and this leaves me puzzled.

for (CCSprite *userspot in gpsUsersSpritesArray){
   id fadein  = [CCFadeTo actionWithDuration:0.05 opacity:255];
   id fadeout = [CCFadeTo actionWithDuration:dotFadeTime opacity:30];
   id seq2 = [CCSequence actions:fadein, fadeout,nil ];
   [userspot runAction:seq2];
}

I have tried to retain the NSMutableArray, but that dit not help either. Also i have tried to force the sprites to be visible and make sure the opacity of the sprites is set to 255, but still no luck.

I may have overlooked something, but i do not think so.

Who helps me out?

Many thanks in advance.


Solution

  • You should not be releasing your sprite. I would think that would cause a crash but it could account for your issue.

    When you create a sprite using something like:

    CCSprite* mysprite = [CCSprite spriteWithFile:@"whatever.png"];
    

    You NEVER should be releasing that. When coding in Objective-C the rule to remember when not using ARC is that you release objects that you alloc/init, new, retain, and copy yourself. You don't do that in your example code. Inside that method it calls autorelease, making your release invalid. The same with adding objects to containers. Those containers take care of themselves and you should not be releasing or doing anything to the retain count outside of those containers on their behalf if you are using convenience methods that call autorelease, like you are in this case. That is invalid. It would be fine if you were using, for example, alloc/init rather than the spriteWithFile method.