Search code examples
c#unity-game-engineaudio-source

AudioSource continues playing old clip after new clip assigned


My game is playing background music and I want to switch it based on game attributes. Here is my solution:

AudioSource audioSource;
[SerializeField] AudioClip audioClipLowZombies;
[SerializeField] AudioClip audioClipMediumZombies;
[SerializeField] AudioClip audioClipHighZombies;
AudioClip currentMusic;

public void ChangeAudio()
{
    if (zombieCount < 10)
    {
        audioSource.Stop();
        audioSource.clip = audioClipLowZombies;
        audioSource.Play();
    }

    if (zombieCount > 10 & zombieCount < 20)
    {
        audioSource.Stop();
        audioSource.clip = audioClipMediumZombies;
        audioSource.Play();
    }

    if (zombieCount > 20)
    {
        audioSource.Stop();
        audioSource.clip = audioClipHighZombies;
        audioSource.Play();
    }
}

The problem is that after changing the clip, the old clip continues playing as well as the new one.


Solution

  • make sure (if you have multiple audio sources) you are referencing the correct audio source. Sadly that's all I can really think of since your code seems fine.