This code works, but I get the following message:
“NullReferenceException: Object reference not set to an instance of an object
SoundManager.OnLevelFinishedLoading (Scene scene, LoadSceneMode mode)”
I only get it at first run (Yes, I have the gameobject attached in first scene).
Then in every other scene everything is fine, no error message.
Also even if I go back to the first scene I don’t get the message back.
It works but I am trying to understand why this happens only when the game loads for the first time.
public class SoundManager : MonoBehaviour {
public AudioClip[] levelMusicChangeArray;
private AudioSource audioSource;
public static SoundManager Instance;
private void Awake()
{
if (Instance == null)
Instance = this;
else if (Instance != this)
Destroy(gameObject);
DontDestroyOnLoad(gameObject);
}
private void Start()
{
audioSource = GetComponent<AudioSource>();
audioSource.volume = PlayerPrefsManager.GetMasterVolume();
}
private void OnEnable()
{
SceneManager.sceneLoaded += OnLevelFinishedLoading;
}
private void OnDisable()
{
SceneManager.sceneLoaded -= OnLevelFinishedLoading;
}
private void OnLevelFinishedLoading(Scene scene, LoadSceneMode mode)
{
int level = scene.buildIndex;
AudioClip thisLevelMusic = levelMusicChangeArray[level];
try
{
if (thisLevelMusic)
{
audioSource.clip = thisLevelMusic;
audioSource.loop = true;
audioSource.Play();
}
}
catch (NullReferenceException e)
{
Debug.LogException(e);
}
}
}