How can I get the active toggle number (not value) from a ToggleGroup?
I have several ToggleGroups of four toggles each. I'm using ActiveToggles() to return the text value of the selected toggle, but I'd much prefer to get an enumerated value, 0-3 in this case (or 1-4, whatever). For example, I'd rather get the number 0 if the first toggle is selected, rather than, say, the string "Novice."
I don't see a way to do that, and I really don't want to set up a bunch of IF statements comparing the returned value to the strings of all the possible choices in order to determine numerically which toggle was selected.
I'm pretty new to Unity. Any help? Thanks.
Answer by lgarczyn · Oct 28, 2019 at 01:36 AM
ActiveToggles doesn't return the text values, but the toggle themselves.
group.ActiveToggles().First()
or
group.ActiveToggles().FirstOrDefault()
Will return the first active toggle. You can then use its name, or use SendMessage to call a function on a script on it, or use an ID stored in a script on the same object, etc.
But what you usually want is to use the Toggle event list to call a function in any script (usually one on the toggle group) to set whatever setting you want.
Answer by j_a_quent · May 10 at 08:12 AM
I get the index like this:
// Get the curren toggle group
ToggleGroup current_toogleGroup = current_toogleGroup_gameObject.GetComponent<ToggleGroup>();
// Get the selected toogle
Toggle selectedToggle = current_toogleGroup.ActiveToggles().FirstOrDefault();
// Get all individual toogles from this toogle group
var toogles = current_toogleGroup.GetComponentsInChildren<Toggle>();
// Loop through all toogles to find the one that is selected
int toogleIndex = -1;
for(int i = 0; i < toogles.Length; i++){
if(toogles[i] == selectedToggle){
toogleIndex = i + 1; // set toogleIndex to i + 1
}
}
Your answer

Follow this Question
Related Questions
Any ideas to optimize this scrip? 2 Answers
How to change button.spriteState.pressedSprite sprite by script - Unity 4.7.1 1 Answer
Using multiple materials on a 2d mesh 0 Answers
Problem with c# script 0 Answers
ObjectParameter Usage in a Custom Skybox 0 Answers