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();
}
}