FIXED!
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
Info
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:
Problem
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);
}
}