I’m using Unity 5, and I’ve changed the code in order to let it work, since OnLevelWasLoaded is deprecated on this version.
My problem is this: the code works, the clips are loaded and played correctly in every game scene as expected, but, after the first entire loop of scenes (Start, Game, Win), I get this error in the console at every other scene change (yes, the music player actually still changes clips and plays them with no issues whatsoever).
NullReferenceException: Object reference not set to an instance of an object
MusicPlayer.OnSceneLoaded (Scene scene, LoadSceneMode loadscenemode) (at Assets/Entities/General/MusicPlayer.cs:27)
UnityEngine.SceneManagement.SceneManager.Internal_SceneLoaded (Scene scene, LoadSceneMode mode) (at C:/buildslave/unity/build/artifacts/generated/common/runtime/SceneManagerBindings.gen.cs:198)
In particular, I noticed that I get this error every time (after the first loop ofc) the code tries to access the music object (i.e. music.Stop(), music.clip, etc.) and that, moreover, I don’t really the music.Stop() method, the new clip starts to play stopping itself the old one.
My code for the Music Player script is as follows:
using UnityEngine;
using System.Collections;
using UnityEngine.SceneManagement;
public class MusicPlayer : MonoBehaviour {
static MusicPlayer instance = null;
public AudioClip startClip;
public AudioClip gameClip;
public AudioClip endClip;
private AudioSource music;
void Awake () {
if (instance != null && instance != this) {
Destroy (gameObject);
} else {
instance = this;
GameObject.DontDestroyOnLoad (gameObject);
music = GetComponent<AudioSource>();
}
SceneManager.sceneLoaded += OnSceneLoaded;
}
void OnSceneLoaded (Scene scene, LoadSceneMode loadscenemode){
//music.Stop ();
if (scene.buildIndex == 0) {
music.clip = startClip;
}
if (scene.buildIndex == 1) {
music.clip = gameClip;
}
if (scene.buildIndex == 2) {
music.clip = endClip;
}
music.loop=true;
music.Play();
}
}
Any help in order to shed some light on that console error will be very appreciated!