[Discussion/Alternative] Music plays fine, but still getting NullReferenceException error

The complete error is:

NullReferenceException: Object reference not set to an instance of an object
MusicPlayer.OnLevelWasLoaded (Int32 level) (at Assets/Scripts/MusicPlayer.cs:53)

Occurs when you’re assigning a different audio clip to music.clip. Also occurs when music.Stop() is used. I’d downloaded the completed project to see if the errors occur and they still do.

I’ve went ahead and set up the audio sources differently without the use of the MusicPlayer script in order to avoid the NullReferenceException errors. Since every scene has their own background music and the music will only play on specific scenes, I added Audio Source components to the hierarchy of every scene, and you can easily use the options in the Inspector for looping and playing on wake.

AudioSource

AudioSourceInspector

It seems like it might have something to do with the scope of ‘music’.
private AudioSource music;

Yeah… I just ran into the same problem in Unity 2017.2, but your solution fixed it so thank you :smiley: .

I think better approach is this described down below.

Solution

I had the same problem with NullReferenceException. After deleting the MusicPlayer object from all the levels except the initial level, I no longer get the error.

Privacy & Terms