Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

Set UI Toggle true by script

Discussion in 'UGUI & TextMesh Pro' started by bozzor, Mar 20, 2015.

  1. bozzor

    bozzor

    Joined:
    Jun 20, 2014
    Posts:
    4
    Hey guy's , i am very new to the Toggle thing, so it would be nice if you can me. ;)

    I have some Toggles in a ToggleGroup wich are supposed to be some Settings.
    My Problem is, that i want to set one to TRUE (last one checked) when loading the settings scene.

    So lets say i have a saved earlier settings in the Playerprefs.. How is it possible to acces the toggle or toggleGroup to give the right toggle a True?

    Thanks for your help ;)
    C# would be great :D
     
  2. Feaver1968

    Feaver1968

    Joined:
    Nov 16, 2014
    Posts:
    70
    I don't think the toggleGroup holds a reference to the toggles that are using it. What I do is have each individual toggle check playerprefs for if it should be on or not in Awake.
    Code (CSharp):
    1. toggleAutoLoadLastSave.isOn = PlayerPrefs.GetInt(kAutoLoadLastSave, 1) == 1;
    Depending on the type of the key you are setting, you will need to do some adjustments to the conditional logic. When one toggle sets on, the others will set off.
     
    bozzor likes this.
  3. SimonDarksideJ

    SimonDarksideJ

    Joined:
    Jul 3, 2012
    Posts:
    1,685
    You are correct @Feaver1968 The toggle group is just a dumb manager that just ensures it maintains a single clicked item (although it's selected group is an enumeration?)

    To turn on/off toggles you have to do it for each toggle. If you wanted a toggle group to work differently, then grab the source from the UI bitbucket repository and make your own :D

    Two points though:
    • Do not try to set or alter UI components in AWAKE as they are not yet initialised. UI components should only be set (at a minimum) in START (or LateUpdate)
    • If you want to store the Toggle that is set from the last run, I'd recommend saving ALL the toggle states using @Feaver1968 's code above.
    I'd also expand on the example slightly with:
    Code (CSharp):
    1. var childToggles = GetComponentsInChildren<Toggle>();
    2. for (int i = 0; i < childToggles.Length; i++)
    3. {
    4.                 childToggles[i].isOn = PlayerPrefs.GetInt(kToggleLastSave + i, 0) == 1;
    5. }
     
    bozzor likes this.