Object missing after changing scenes

Hey Guys,

i’m trying to add a “Mute”-Button to my game.
the button handles the GameObject “Music Player” which has the following script:

using UnityEngine;
using System.Collections;

public class MusicPlayer : MonoBehaviour
{

	public static MusicPlayer instance = null;
	private static bool pause = false;

	void Awake ()
	{
		if (instance != null) {
			Destroy (gameObject);
			Debug.Log ("Duplicate Selfdestuct");
		} else {
			instance = this;
			GameObject.DontDestroyOnLoad (gameObject);
			Debug.Log ("Sound played");
		}
	}
	
	// Use this for initialization
	void Start ()
	{
	}
	
	
	// Update is called once per frame
	void Update ()
	{	
		if (pause) {
			audio.Pause ();
		}
	}
	
	public void PauseMusic ()
	{
		//check for audio component first
		if (!pause) {
			//if audio is playing then pause it, else unpause it
			pause = true;
			Debug.Log ("Audio is Paused");
		} else {
			pause = false;
			audio.Play ();
			Debug.Log ("Audio is Unpaused");
		}
	}
}

So my buttons on Click () ist adjusted to MusicPlayer.PauseMusic and all work fine. Music is (un)muted every time i click - behavior is as i wish.

BUT if i change scenes the music player destroy itself (because i want persistent background music) and button is missing it’s previous Game Object.

What can i do?

Greetings

@Elunius Hello there.

OK, the only thing you need to do it’s use a method or set in the method where you load you new scene to do not destroy the selected game object, I made this some time a go, just like you I did a button to mute on/off an audio component (background music), so, when you go to the next level the music goes on, if you are trying to keep some elements from one scene into another, this is the best way to achieve that, remember, when you are loading the next scene, cheers.

I figured it our myself by making a new script and adding it to the mute button
using UnityEngine;
using System.Collections;

public class Mute : MonoBehaviour
{

	private MusicPlayer mp;

	void Start ()
	{
		mp = GameObject.FindObjectOfType<MusicPlayer> ();
	}

	void Update ()
	{
	}
	
	public void PauseMusic ()
	{
		//check for audio component first
		if (!MusicPlayer.pause) {
			//if audio is playing then pause it, else unpause it
			MusicPlayer.pause = true;
			mp.audio.Pause ();
			Debug.Log ("Audio is Paused");
		} else {
			MusicPlayer.pause = false;
			mp.audio.Play ();
			Debug.Log ("Audio is Unpaused");
		}
	}
}