1
votes

I have a game which has many unique units, and each unit has its own sprite sheet (because each unit has several animations), meaning there may be upwards of a dozen sprite sheets used by the game on any given scene. When the scene with the units is created, the initialization of all these assets takes a lot of time (a couple seconds). Specifically, the UI is locked while this code is run:

  NSString *unitSheetName = [self getUnitSheetName];
  [[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:unitSheetName];

  CCSprite *frame = [CCSprite spriteWithSpriteFrameName:kDefaultFrameName];
  // etc...

However, if I then pop the scene, and then create a new version of the same scene (and push it), the loading takes a fraction of the time (the UI does not lock). Thus, it seems the UI locking is due to the initial caching of the sprite sheets...

My hope was that I'd be able to avoid this lag by calling the CCSpriteFrameCache's addSpriteFramesWithFile method while the game is starting up, but this does not seem to work. Despite doing this, the initial load still takes a long time.

Is there any good, effective way to preload the assets? I don't mind adding a second or two to my startup loading screen, if only I can be sure that the UI will later not be locked when the scene is pushed...

1
delay is due to texture loading, use texture cache's addImage: to preload the texture - LearnCocos2D
Thanks, that did the trick! I guess I expected that the CCSpriteFrameCache would do this in the process of caching. I'll add an answer below with my code, for others. - Zane Claes

1 Answers

1
votes

Per @LearnCocos2D's reply, above, here's how to properly and fully pre-load a sprite sheet, (fpSheet is the file path of the sheet):

  [[CCSpriteFrameCache sharedSpriteFrameCache] addSpriteFramesWithFile:fpSheet];

  NSDictionary *spriteSheet = [NSDictionary dictionaryWithContentsOfFile:fpSheet];
  NSString *fnTexture = spriteSheet[@"metadata"][@"textureFileName"];
  [[CCTextureCache sharedTextureCache] addImage:fnTexture];