should I cache textures in properties in sprite kit?
Asked Answered
M

0

0

I am using atlases for the image assets in my game. I am preloading all my atlases at the beginning of my Game Scene with SKTextureAtlas preloadTextureAtlases which made a big difference when I started using it. Here is my question:

Should I create a property for each texture that is going to be applied again and again to spawned monster or pickup sprites? Or is it completely unnecessary overhead because I am preloading my atlases in my Game Scene?

The below are 2 very simple examples in a Monster class.

Cache Texture:

- (id)initWithSize:(CGSize)size
{
    if (self = [super init]) {
        SKTextureAtlas * atlas = [SKTextureAtlas atlasNamed:monsterAtlas];
        self.monsterFighterTexture = [atlas textureNamed:@"monster-fighter"];
    }
    return self;
}

- (Monster *)monster
{
    Monster * monster = [Monster spriteNodeWithTexture:self.monsterFighterTexture];
    return monster;
}

Don't cache texture.

- (Monster *)monster
{
    SKTextureAtlas * atlas = [SKTextureAtlas atlasNamed:monsterAtlas];
    Monster * monster = [Monster spriteNodeWithTexture:[atlas textureNamed:@"monster-fighter"]];
    return monster;
}
Mercedes answered 18/1, 2015 at 6:49 Comment(3)
When you use a texture atlas each texture generated with [atlas textureNamed:@"monster-fighter"] will be a reference to the same texture object in memory.Acting
To expand on what Okapi already stated, once you load a texture atlas and have at least one strong reference to it, the atlas will stay in memory. There are several ways of doing this. For example, you can create a singleton to hold all your atlases or make them class properties. It's really a matter of personal preference.Exterritorial
Great. Thanks. So instead of caching individual textures I should just cache the atlas in a property and access textures with textureNamed.Mercedes

© 2022 - 2024 — McMap. All rights reserved.