In my main menu scene, I have both the AudioListener and an AudioSource on the same GameObject, set to DontDestroyOnLoad. When I start the game from the menu, I play a sound using myGlobalAudioSource.PlayOneShot
, fade the menu out and then load the first gameplay scene. For some reason, this interrupts the sound that is still being played, although neither AudioSource nor AudioListener are unloaded. Any way to fix this easily, or do I need to hook up my own DontDestroyOnLoad audio source pool for these sounds?
I use the same technique but I never came across such an issue. You may need to provide a sample scene.
Thanks @bakioztepe , that’s good to hear - maybe I’m just doing something stupid. I’ll double-check.
The issue is that PlayOneShot does not count as a reference to the AudioClip. If the last Unity Object that holds a reference to the Clip is destroyed, the clip will get unloaded and cut off. Somebody already mentioned a similar thing 10 years ago here: PlayOneShot and Resources.UnloadUnusedAssets()
There doesn’t seem to be any open bug related to this, so I will report it and link it here soon. For the time being, I will probably work around this by instantiating my own pooled AudioSources (DontDestroyOnLoad) which then hold the reference as long as the clip is playing.
Can you believe it?
[RequireComponent(typeof(AudioSource))]
public class GlobalAudio : MonoBehaviour
{
[SerializeField] private AudioSource _audioSource = null;
public void PlayOneShot(AudioClip clip)
{
_audioSource.PlayOneShot(clip);
StartCoroutine(HoldHostage(clip));
}
private IEnumerator HoldHostage(AudioClip clip)
{
yield return new WaitForSeconds(clip.length + 1.0f);
}
}
Interesting however makes sense. This is probably by design.
You can’t expect AudioClip to hold references under the hood because you can call PlayOneShot() multiple times, in parallel.
You can solve it by creating a persistent object, that has a script which references these clips.
Or you can load the clips using Resources.Load and store the loaded clips in a static class or singleton object.
Yep, and each OneShot should increase the reference count by one and decrease it when it’s done playing. I’d definitely expect this to happen under the hood. Anyway, worked around it, time to move on
Here is the respective issue in Unity’s tracker: