How can I reference a Toggle?

Hello community.

How can I reference a toggle with the new canvas UI? I’ve tried to reference by name and tag but it doesn’t Works.

Here’s a piece of my code.

 public void OpcionesKeyboard()
    {
        accelerometerJugador1.gameObject.name.Equals("accelerometerJugador1");
        keyboardJugador1.gameObject.name.Equals("keyboardJugador1");

        if (keyboardJugador1.onValueChanged.Equals(true))
        {}
else if (keyboardJugador1.onValueChanged.Equals(false))
        {
            accelerometerJugador1.onValueChanged.Equals(true);
        }

or

public void OpcionesKeyboard()
        {
            accelerometerJugador1.gameObject.tag.Equals("accelerometerJugador1UI");
            keyboardJugador1.gameObject.tag.Equals("keyboardJugador1UI");
    
            if (keyboardJugador1.onValueChanged.Equals(true))
            {}
    else if (keyboardJugador1.onValueChanged.Equals(false))
            {
                accelerometerJugador1.onValueChanged.Equals(true);
            }

Thanks for the help.

Regards.

You need to use using UnityEngine.UI at the top of the file. Then you can just create a public Toggle myToggle field that can be assigned in the inspector.

You will probably want to use GameObject.Find() to locate your Toggle by name:

var myToggle : GameObject;
// This will return the game object named Hand in the scene.
hand = GameObject.Find("myToggle");

Other similar functions (such as FindGameObjectsWithTag, FindObjectOfType, FindObjectsOfType, etc.) are listed in the manual entry for GameObject.

To find all active Toggles by tag:

Toggle[] myToggles = GameObject.FindGameObjectsWithTag ("myToggleTag");

To find all Toggles in the scene (irrespective of tag), you can use:

Toggle[] myToggles = FindObjectsOfType(typeof(Toggle)) as Toggle[];

Hope this helps.

  • P.S. To expose a variable in the Inspector, you will need to make it Public.

  • P.S.2 I’m new to Unity as well. Treat my answers with some suspicion as they might not be correct/efficient.

GameObject toggle;
Toggle soundToggle;

void Start()
{
toggle = GameObject.FindGameObjectWithTag(“Sound”);
soundToggle = toggle.GetComponent();
SetToggles();
}

void SetToggles()
{
if (soundOn)
{
soundToggle.isOn = true;
}
else
{
soundToggle.isOn = false;
}
} // end SetToggles()