I'm trying to create a preload, but i don't know how to implement the code of this topic in cocos2d iphone v3. Since CCTextureCache has changed to CCTexture, and doesn't have sharedTextureCache property anymore.

@interface TextureHelper : NSObject
+ (CCTexture2D *) textureForImageNamed:(NSString *) imageName;
@end

@implementation TextureHelper
+ (CCTexture2D *) textureForImageNamed:(NSString *) imageName {
return [[CCTextureCache sharedTextureCache] textureForKey:imageName];
}

// or could read from a directory...
NSArray *imageNames = @[
@"myImage1.png",
@"myImage2.png"
];

for (NSString *imageName in imageNames)
}
@end


Well, one way is to load the textures and keep a reference to them ourself. You could reimplement your code to something like:

@interface TextureHelper : NSObject
- (CCTexture2D *) textureForImageNamed:(NSString *) imageName;
@end

@implementation TextureHelper
{
}

- (CCTexture *) textureForImageNamed:(NSString *) imageName
{
// TODO: Lookup loadedTextures and find the requested one.
// Return a pointer to it. Probably use a NSDictionary...
}

- (CCSprite *) spriteForImageNamed:(NSString *) imageName
{
// Create a sprite using the whole contents of the texture:
CCTexture * tex = [self textureForImageNamed:imageName];
if (!tex)
{
// TODO: Handle failure
}

CCSpriteFrame * frame = [tex createSpriteFrame];
CCSprite * sprite = [CCSprite spriteWithSpriteFrame:frame];
return sprite;
}

{
NSArray *imageNames = @[
@"myImage1.png",
@"myImage2.png"
];

for (NSString *imageName in imageNames)
{
CCTexture * tex = [CCTexture textureWithFile:imageName];
}
}

@end


You'll probably want to use a dictionary to store the textures and index them by name, but you can get the ideia from the code above. CCSprite also has spriteWithTexture / initWithTexture that you can use in conjunction.

• Thanks! How should I reference the loadedTextures when creating the CCSprite? I'm trying @"img.png" and img.png and none works – Filipe Ferminiano Mar 31 '14 at 11:01
• Sorry @FilipeFerminiano, I didn't quite follow your question. I've edited the code to include a method that directly creates a sprite with the contents of a preloaded texture. If your problem is that the textures are not being found/loaded, then you probably forgot to add them to your project on Xcode. – glampert Mar 31 '14 at 14:41