Unity: Multiple Instances sharing one AudioSource

856 Views Asked by At

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

There are 1 best solutions below

2
On BEST ANSWER

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.