Unexpected GUI.toggle behaviour

I’m curious why the first does not work as expected but the second (more long-winded) does. The checkbox is added to canvas rather than being created in the script.

	public void toggleMusic(bool toggle)
	{
		Debug.Log (toggle);
		if(!toggle)
		{
			Debug.Log("Stop");
			Music.Stop();
		}
		else
		{
			Debug.Log("Play");
			Music.Play();
		}
	}

In the above case, when I click on the button, toggle is always false and it is ‘Stop’ that is printed to the console. No matter whether the checkbox is checked or not.

	public void toggleMusic(bool toggle)
	{
		GameObject Toggle = GameObject.FindWithTag("Toggle");
		bool state = Toggle.GetComponent<Toggle>().isOn;
		Debug.Log (toggle);
		if(!state)
		{
			Debug.Log("Stop");
			Music.Stop();
		}
		else
		{
			Debug.Log("Play");
			Music.Play();
		}
	}

Here, if I need to check the isOn value, what’s the point of linking to this script in the inspector for the toggle button?

Almost @DiegoSLTS, you are right that @sirfragalot has the bool value from the function selected but it is perfectly possible to pass the bool value isOn.

I created a simple test like @Baste did and added a function called ToggleUpdate but when I added the link to that function I picked the ToggleUpdate that doesn’t show the bool.

40523-togglebool.png

So the one at the top, that uses the bool from the actual toggle rather than allow you to set the bool in the inspector. Just added functionality for the UI.

The value for “toggle” on toggleMusic is the value that you set on the checkbox in the inspector, NOT the value of the toggle itself. That’s why your second method works, you’re actually getting the toggle’s isOn value there.

If you don’t want to make that (I wouldn’t either) you can bind a property instead of a function.

public bool toggleMusic {
    set {
        if(!value) //in case you've never used properties, "value" has the value you set to the property, in this case, the isOn value of the toggle
        {
            Debug.Log("Stop");
            Music.Stop();
        }
        else
        {
            Debug.Log("Play");
            Music.Play();
        }
    }

}

Add your method to the toggle as Dynamic Bool. It will be under the grayed out Dynamic Bool at the top of the drop down menu. You don’t have to do this voodoo.