DaveB DaveB - 1 year ago 69
iOS Question

SpriteKit properly handling sounds

I have a SpriteKit game where I have a number of different Sprites Lasers, Planes, etc. A number of these Sprites have a sounds that will play whenever they are visible. Right now I play the sound in the SKSpriteNode itself. This probably isn't what I want because if I have I have 50 of the same sprites, they'll all be playing the same sound and gobbing resources. However, I'm not really sure where would be the best place to play the the sound, because for some of these sprites I would need to check if it should be playing or not. I suppose I could put the sounds in the the GameScene and loop through all sprites during every update to determine what sounds should and should not still be playing, that way there would only be one instance of every sound. I was hoping to keep all the sprite code within the sprite itself, but this would solve the issue with multiple instances of the same sound playing. Is this the correct way to handle sounds?

Answer Source

It is hard to give you a proper code example without seeing your code. You can however get the gist of what you can try with what I have below.

In MyScene add a property BOOL propSound.

Whenever you create a new plane and wonder about adding the prop sound do something like this:

if(propSound == false)
    propSound = true;
    // add your code to play prop sound

If you add every newly created plane sprite into a NSMutableArray like this [yourArrayName addObject:newPlane];, you can check the array count every time you remove a plane in order to know if the last plane was removed and the sound needs to be stopped.

if([yourArrayName count] == 0)
    propSound = false;
    // add your code to stop prop sound