- Home /
How to destroy audio when looping back to main screen
Hi All
I have setup my game to have an AudioListner object on each scene. Helps with playing around with different tracks in different scenes. For now I've just got 2 playing. Main menu then Game music (when starting the game. the main menu is removed) and continuing to the end with final screen and even lose screen playing through. On the lose screen or end screen, I get routed to the main menu but the audio continues and the Main menu audio plays together. I want the main menu to play only and the other game sound to die. How can I do this?
Current code:
public class AudioListener : MonoBehaviour { AudioSource audioSource; void Start() { Scene currentScene = SceneManager.GetActiveScene(); string sceneName = currentScene.name;
if (sceneName != "Main Menu")
{ DontDestroyOnLoad(this);
audioSource = GetComponent<AudioSource>();
}
else
{ Destroy(this); }
}
}
I've seen some people use this singleton but it deletes the AudioLisener game object from my GameStart and I wont have my new track playing.
public class MusicPlayer : MonoBehaviour
{
private static MusicPlayer _instance ;
void Awake()
{
//if we don't have an [_instance] set yet
if(!_instance)
_instance = this ;
//otherwise, if we do, kill this thing
else
Destroy(this.gameObject) ;
DontDestroyOnLoad(this.gameObject) ;
}
}
Answer by Magso · Dec 02, 2020 at 01:46 PM
You could use a single audiosource and swap the audio clip for the scenes.
//When another scene loads
audio.clip = sceneMusic;
audio.Play();
I'm still new to coding here so sorry if I ask some silly questions but how do I actually add that to my code? Should I be indexing? I haven't tried playing each scene individually besides attaching to the object itself.
Also, wont I need to define what audio is in each scene? At the moment I have: $$anonymous$$ain $$anonymous$$enu [0] --- Intro clip here Level 1 [1] ---- Start clip here Level 2 [2] Level 3 [3] End Screen [4] --- back to main menu Game Over [5] -- back to main menu
It has the DontDestroyOnLoad()
method so it can keep all the music AudioClip references in '$$anonymous$$usicPlayer', you can do this either with a list or an array.
The $$anonymous$$usicPlayer script can then have a custom function like this
void Change$$anonymous$$usic(int audioClipIndex)
{
AudioSource audio = GetComponent<AudioSource>();
audio.clip = Your $$anonymous$$usic List [audioClipIndex];
audio.Play();
}
Now when loading a new scene, reference the GameObject with the $$anonymous$$usicPlayer script and call the custom function.
The $$anonymous$$usic Player Object .GetComponent<$$anonymous$$usicPlayer>().Change$$anonymous$$usic(The Index Number);
Scene$$anonymous$$anager.LoadScene(...)
Your answer
Follow this Question
Related Questions
Sound not playing 1 Answer
Weird Looping of Audio. 0 Answers
Unity not playing audio 0 Answers
Help with a low health script 1 Answer
How can I get a split-up sound to properly loop with an animation? 1 Answer