I have a bunch of animations contained in about 10 texture atlases. The project I am working on has a bunch of bad guys running around so obviously I shouldn't duplicate all the animations each time a bad guy class is instantiated.

Should I use (option A) a singleton class to store ALL my bad guy animations and have it return a specific animation whenever needed to a bad guy class or do I insert (option B):

static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
// do animating stuff here...
});

into my bad guy class? OR is this a case of tomato vs. tomatoe ?

P.S. I REALLY suck at working my own class methods so if option B is the answer, a working example would be oh so greatly appreciated!

有帮助吗?

解决方案

Maybe take a look at Apple's code:Explained Adventure. At section "Loading Shared Character Assets", they use:

static dispatch_once_t onceToken;

dispatch_once(&onceToken, ^{

    sSharedIdleAnimationFrames = APALoadFramesFromAtlas(@"Boss_Idle", @"boss_idle", kBossIdleFrames);
    // (Load other animation frames)
    sSharedDamageEmitter = [SKEmitterNode apa_emitterNodeWithEmitterNamed:@"BossDamage"];
    sSharedDamageAction = [SKAction sequence:@[
        [SKAction colorizeWithColor:[SKColor whiteColor] colorBlendFactor:1.0 duration:0.0],
        [SKAction waitForDuration:0.5],
        [SKAction colorizeWithColorBlendFactor:0.0 duration:0.1]]];
}

其他提示

To answer the question of using a singleton vs dispatch_once, dispatch_once is not a singleton by itself, instead it is often used as a way of instantiating a singleton within the singleton accessor method. It will ensure that the block is only ever executed one time for a program's life. We can use this to ensure we only create our object one time.

Example

+(instancetype)sharedInstance {
    static MySingletonClass *s_sharedPointer = nil;
    static dispatch_once_t onceToken;
    dispatch_once(onceToken, ^{ // ensures we only ever create one MySingletonClass
        s_sharedPointer = [[MySingletonClass alloc] init];
    });
    return s_sharedPointer;
}

I am not as familiar with the nuances of Spritekit or animations, so I am unable to provide much detail regarding your specific problem, but I hope my answer provides some direction. Hopefully someone else who knows more about working with animations will answer with better insight on a good class design.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top