I have a game im trying to code in Unity3d. I already have a DontDestroyOnLoad function running to play a music when the game loads into the main menu. But lets say I want to play a different song in game, how would I go about doing this? This is my music playing script.
using UnityEngine;
public class MusicManager : MonoBehaviour
{
private static MusicManager musicManagerInstance;
// Start is called before the first frame update
void Awake()
{
DontDestroyOnLoad(this);
if(musicManagerInstance == null){
musicManagerInstance = this;
}
else{
Destroy(gameObject);
}
}
}
I think that you should do something like this
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
public class MusicManager : MonoBehaviour
{
private static MusicManager musicManagerInstance;
public AudioClip landSong;
public AudioClip watersong;
// Start is called before the first frame update
void Awake()
{
AudioSource audioSource = GetComponent<AudioSource>();
Scene level = SceneManager.GetActiveScene();
string levelName = level.name;
DontDestroyOnLoad(this);
if(musicManagerInstance == null){
musicManagerInstance = this;
}
else{
Destroy(gameObject);
}
switch(levelname)
{
case "landScene":
audioSource.clip = landSong;
break;
case "waterScene":
audioSource.clip = waterSong;
break;
default:
break;
}
audioSource.play();
}
}
This just checks the scene’s name and plays the corresponding song. I’m not sure if it will work as I have not tested it.
Hey @NatsuSuika, hajime mashite!
Ideally you should have 2 AudioSources to do it properly, so you can fadeout the one playing and fadein the new one.
The Awake above on @ChocoboyYT solution will not be called multiple times (on each scene), it’s only called the first time when the object is created (scene 1). You need instead to listen to the scenes loading.
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
public class MusicManager : MonoBehaviour
{
private static MusicManager musicManagerInstance;
public AudioClip landSong;
public AudioClip watersong;
private AudioSource audioSource;
void Awake()
{
DontDestroyOnLoad(gameObject);
audioSource = GetComponent<AudioSource>();
Scene level = SceneManager.GetActiveScene();
PlaySongBySceneName(level.name);
}
void OnEnable()
{
SceneManager.sceneLoaded += OnSceneLoaded;
}
private void OnSceneLoaded(Scene scene, LoadSceneMode mode
{
PlaySongBySceneName(scene.name);
}
private void PlaySongBySceneName(string levelname)
{
switch(levelname)
{
case "landScene":
audioSource.clip = landSong;
break;
case "waterScene":
audioSource.clip = waterSong;
break;
default:
// Do whatever
break;
}
audioSource.Play();
}
}