- Home /
Unity new GUI, how to nicely trigger grouped toggleButton callback
Hi, I have issues when connecting a function into On Value Changed callback :
I have a Panel, with a "Toggle Group" component, which contains two toggleButtons, that work exclusively.
In each toggleButton, I can plug a function with (only?) one argument, and what I did is put an int to notify an index of the user choice (bad design?).
But I see that the function is triggered twice, one for the old active toggleButton (for disabling event I imagine), and next for the new ticked one... It is bad for me, because all my logic further is executed twice.
Worse, if I put a gameObject as argument of the callback function, I will not be able to put an int for index, so I will not be able to know the user choice... (.IsOn is true for Both callback executions)
So, how can I nicely trigger (the same) function from a grouped toggleButton, and know what gameObject is ticked (and only once per user click)
Thank you !
Answer by cosmogonies.net · Feb 22, 2015 at 06:54 PM
Anyway, I managed to do it in a tricky way :
// From public properties, MyPanel is the panel which contains all the grouped toggleButton:
// Each toggleButtons are connected to the function "OnToggle_Language", with a unique index for each as int parameter
public void OnToggle_Language(int _LanguageIndex)
{
GameObject EventSource = UnityEngine.EventSystems.EventSystem.current.currentSelectedGameObject;
Toggle[] Toggles = MyPanel.GetComponentsInChildren<Toggle>() as Toggle[];
for (int i = 0; i < Toggles.Length; i++)
{
if( Toggles[i].gameObject == EventSource)
if(Toggles[i].isOn)
if(i==_LanguageIndex)
Debug.Log (i + "is trigerred");
}
}
Now, the log is only triggered once, but I'm quite sure that this is a bad workaround and there's a cleaner way...
Answer by AminAghajoon · Jul 27, 2015 at 04:34 AM
Maybe the better way is this(attach this to toggle group object) :
public void OnAnyToggleValueChanged()
{
var toggleGroup = GetComponent<ToggleGroup>();
if (toggleGroup.AnyTogglesOn()) {
var activeToggle = toggleGroup.ActiveToggles().First();
// Do something with active toggle
}
}
Your answer
Follow this Question
Related Questions
GUI window popup button 1 Answer
Little help with GUI Toggle needed 1 Answer
EditorGUI elements require minimum size of 24px? 0 Answers
GuiTexture toggle on keypress. 2 Answers