I have a game built in Unity. The game plays music continuously, which can be muted on button press on the scene. This works fine using the below code:
MuteButton.cs
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
public class MuteButton : MonoBehaviour {
public GameObject audioObject;
private AudioSource audioSource;
void Start()
{
Button b = gameObject.GetComponent<Button>();
b.onClick.AddListener(Pause);
}
void Pause() {
Debug.Log("mute toggle");
audioSource = audioObject.GetComponent<AudioSource>();
if(!audioSource.isPlaying) {
audioSource.Play();
} else {
audioSource.Pause();
}
}
}
However, when the player loses the game restarts by reloading the scene, using this code:
public void Restart()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
}
In order to keep the music running I have attached the following script to my music game object:
using UnityEngine;
using System.Collections;
public class Music : MonoBehaviour {
static Music instance;
void Start() {
if(instance == null)
{
instance = this;
DontDestroyOnLoad(gameObject);
}
else if (instance != this)
{
Destroy(gameObject);
}
}
}
All working fine up until now. Once the scene is reloaded when the user tries to mute the music I get the following:
MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it.
Your script should either check if it is null or you should not destroy the object.
I understand that the error is that I'm trying to mute a now non-existent game object, but how can I pause the music if this is the case?