Toggle

Unity UI Toggle

Unity's basic toggle setup is great for most uses, however if you want to be able to change the 'Is On' value from code without triggering 'On Value Changed' event you'll have to use the 'Event Trigger' component.

For example I want to save an int to the player's preference that was representing the state of the trigger. 0 for off and 1 for on. I'm saving it here cause the next time the scene loads I want to look at the preference and have my toggle set accordingly.  

So in the 'Start' function I'll set the toggle state based on the PlayerPrefs value, and then when the toggle is triggered I'll change the value accordingly. Code would look something like this:

using UnityEngine;
using UnityEngine.UI; //To access 'Toggle'
using System.Collections;

public class exampleToggleScript : MonoBehaviour {
    
    public Toggle toggle;

    void Start () 
    {
        toggle.isOn = PlayerPrefs.GetInt("toggleKey") == 1;
    }


    public void toggleExampleTrigger()
    {
        //Toggle triggered do something.
        if(toggle.isOn)
            PlayerPrefs.SetInt("toggleKey", 1);
        else
            PlayerPrefs.SetInt("toggleKey", 0);
    }
}

The problem occurs when the 'toggleExampleTrigger' is linked to the 'On Value Changed' option of the Toggle component. Every time the scene loads and it changes the value based on the preference setting it will also trigger 'toggleExampleTrigger', causing the toggle state and the preference value to be out of sync.

To fix this I don't want to use the 'On Value Changed' event at all. Instead add the 'Event Trigger' component. 

Using the 'Pointer Click' event type to link 'toggleExampleTrigger' to, I'll avoid this sync issue and be able to change the state of the toggle in code without trigger an unwanted event.