- Home /
NullReferenceException only at first run
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);
}
}
}
Answer by hexagonius · Dec 06, 2018 at 12:09 PM
that's because OnEnable is called prior to start and in turn receives the OnLevelFinishedLoading call prior to start sich is itself called before Start's are called. And since you use the singleton pattern, after the first NullReferenceException, it knows it's reference and the problem won't appear again.
as a fix and future recommendations, do GetComponent calls performed on itself in Awake.
Thank you for your answer @hexagonius. I changed the order, from Start() to Awake(). What I mean is that I put audioSource = GetComponent(); in Awake() and it worked!
Thank you!
if you meant changing the order of how the methods are written in the file, then you should have a course in program$$anonymous$$g really quick.
No, what I meant is the order in life cycle that I had it GetComponent in Start() ins$$anonymous$$d of Awake(). I edited my comment to make it clear.
Answer by R4y-GM · Dec 06, 2018 at 12:11 PM
u selected the prefabs?
catch (NullReferenceException e)
{
Debug.LogException(e);
} //what this does? I do not understand
Your answer
