0
votes

I am building a simple 2D game, basically a clone of Plants vs. Zombies, for learning purposes.

I can add different defenders to my game and I want one of my defenders to play an ongoing sound when it is instantiated in the game.

So the sound should be awake on start and looping until the defender is killed. The problem is, that if I instantiate more than one of these defenders in the game, they will all play the same sound, which stacks up.

I feel like I have tried everything and it comes down to this problem. If I put the AudioSource on the defender itself, the sounds will stack up. If I put the AudioSource in different GameObject then the sound does not stop when the defender is destroyed.

What am I missing? I tried to create a static AudioSource for the defender class but this didn't work either. I tried to connect this with the health of the defender, switching a boolean once the defender has a health of 0 (=dead) but none of my solutions did work.

This is my last script attempt on the Defender.

private static AudioSource audioSource;

// Use this for initialization
void Start () {
    audioSource = gameObject.GetComponent<AudioSource>();
    if (!audioSource.isPlaying){
        audioSource.Play();
    }
}
1
"the sound does not stop even though the defender has already been destroyed." The sound won't stop itself. You have to stop it with audioSource.Stop(). - Programmer
But when? When to stop the sound? As I write, I tried to connect it with the health of the defender, stopping the sound once the health is down to zero but that didn't work either. - marvinb89
You stop the sound when you want to. I don't know when you want to stop the stop so I can't help but my first comment shows how to stop the sound - Programmer
The question is irrelevant to the actual problem you are facing. Therefore has no use for future readers. I recommend you to edit or delete the question. - Bizhan
@marvinb89 let me know if it is clear my solution. Or if you were looking for something else - Ignacio Alorre

1 Answers

2
votes

As @Programmer said you need to stop the Audio Source like this:

audioSource.Stop()

Now when. As I understand you want to have a unique audio source playing as long as one of the defenders is still alive. So what you can do is to create a counter in that non-defender GameObject you mentioned. Also a public method to modify this counter from the defenders' scripts in the following way:

  • Every time a new defender is instantiated (in their start method for example), you add a +1 to the counter
  • Every time a minion is destroyed you add a -1.

Then you check:

  • If the counter > 1 then you add:

    if (!audioSource.isPlaying){ audioSource.Play(); }

  • In case the counter is == 0 then you stop it.

In case you have several types of minions, with different sounds, you can have different counter and different methods to be invoked from the minions script to start and play different sounds.