PLEASE HELP!! Object reference not set to an instance of an object at ChangeMasterVolume.Update


Here’s how I fixed the problem.

void Update () {
		if (VolumeSlider != null) {

			myMusic.volume = VolumeSlider.value;


I made it so if the VolumeSlider (Slider) was equal to null, it would run the same thing as before (myMusic.volume = VolumeSlider.value). Thanks to @IvanDrake


So I’m making a slider that changes the overall volume of my game. The only music that is being used in the actual game is some background music, and that’s it. No other sounds or anything.

This is the code that I am using for an empty object in my Main Menu, where the slider is located.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ChangeMasterVolume : MonoBehaviour {

	public Slider MasterVolume;
	public AudioSource myMusic;

	void Update () {

		myMusic.volume = MasterVolume.value;


Here’s what the inspector of the empty object (AKA MusicManager) that contains the code looks like:


And I’m getting this error in the console when I press the play button:

NullReferenceException: Object reference not set to an instance of an object at ChangeMasterVolume.Update ()

Extra Info

Also I would like to note that I recently added another script called “Continuous Music” that allows the music to continuously play between scenes. Not sure if this is relevant, but I’ll add the script anyway:

using System.Collections;
using UnityEngine;

public class ContinuousMusic : MonoBehaviour {

	void Awake () {
		GameObject[] objs = GameObject.FindGameObjectsWithTag ("music");
		if (objs.Length > 1)
			Destroy (this.gameObject);
		DontDestroyOnLoad (this.gameObject);

There may be some conflict between the two scripts. Maybe set your MasterVolume slider by code, rather than manually. If the music manager is being destroyed, the new one may not be set.

Also, might be good to add an ‘if’ statement before setting the volume value to check that the slider exists. You can add an ‘else’ with a custom error message to add more detail. That way it won’t freeze the game and will give you a better idea of what’s going wrong.