Mute Toggler

Hi guys, i’m in trouble with a toggler in unity.
What i’m trying to do is to set to 1 the variable “mute” (of another script) when a toggle in the options menu is false, and to set it to 0 when it is true. Then the mute variable controls the audiolistener.

Thanks for help :slight_smile:

Here’s my code:

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

public class Mute : MonoBehaviour {

GameObject toggle;

void Start () {

	toggle = GameObject.Find ("MuteToggle").GetComponent<Toggle> ();	
}


void Update () {
	if (toggle.isOn = true) {

		SoundController.muted = 0;
	} 
	else {
		SoundController.muted = 1;
	}

}

}

so I would recommend doing something more like this

public class Mute : MonoBehaviour {

       Toggle toggle;
 
       void OnToggled(bool b) 
       {
           if (b) 
                SoundController.muted = 0;
           else 
               SoundController.muted = 1;
       }


      void Awake()
      {//try not to use gameobject.find since it will search everything in the scene and generally inefficient
           toggle = GameObject.Find ("MuteToggle").GetComponent<Toggle> ();
      }


       void Start () 
       {
            toggle.onValueChanged.AddListener(OnToggled);
       }
}

essentially the difference is that instead of doing it in update, this will only fire an event whenever the toggle is toggled, and then it will run OnToggled. that onvaluechanched event will send a boolean, and you can use that boolean to know whether or not the toggle is on or not.

you missed a evaluating equals and used an assignment equals on line 10. so change line 10 to

if (toggle.isOn == true) {