Add a Music On/Off button to "Easy Menu" asset in Unity 3d store

by sunil ravulapalli /15. March 2014 07:06 /unity /Comments (0)

The "Easy Menu" I am referring to is

In MenuElement.js, In the ElementTypes enum just below image add "button_MusicSwitcher" as a new option.

In the function OnGUI add this code

case ElementTypes.button_MusicSwitcher:
 if (GUI.Button (Rect (currentPosition.x, currentPosition.y, size.x, size.y), GUIContent (caption, icon)))
	if (!locked) {
		Camera.main.GetComponent(AudioListener).enabled =  !Camera.main.GetComponent(AudioListener).enabled;
		var musicOnOff = PlayerPrefs.GetString("MUSIC");
		if (musicOnOff == "OFF")
			PlayerPrefs.SetString("MUSIC", "ON");
			PlayerPrefs.SetString("MUSIC", "OFF");


Usually, if you have background music in a game scene you will have an "Audio source" component attached to game object like the "Main Camera" and you would have the option "Play On Awake" checked.

Uncheck "Play On Awake" option and modify code so that you start the music using code. It will look something like this:

public class MainCamera : MonoBehaviour {

	// Use this for initialization
	void Start () 
		string musicOnOff = PlayerPrefs.GetString("MUSIC");
		audio.loop = true;        
		if (musicOnOff == "OFF")

		Debug.Log("Hello:" + PlayerPrefs.GetString("MUSIC"), gameObject);		
	// Update is called once per frame
	void Update () {