Radio buttons

I would like to make a radio button control out of multiple toggle controls. However, since each of the toggle controls are independent of each other you can select multiple ones, I only want the user to be able to select one at a time.

I know I can do this with brute force in scripting by storing the last state of the toggle, testing for change, and setting all the others to false, but there should be a better way.

If my description of a radio button is confusing here is a wikipedia link. Radio button - Wikipedia

you can use SelectionGrid with toggle style to realize it.

GUILayout.SelectionGrid(0,text,count,"toggle");

or ToolBar is also Ok

3 Likes

Thank you, works great!

Actually, I got it without SelectionGrid. The code isn’t that tricky :roll:

I can’t believe i fiddled farted with this for hours, when “unitymatrix” had the perfect solution!

Thanks!

-Raiden

append: you should also check this, just to be sure how to manage the selected item

Toggle will give you checkboxes, use EditorStyles.radioButton instead

var text = new string[] { "option1", "option2", "option3", "option4" };
  GUILayout.SelectionGrid(0, text, 1, EditorStyles.radioButton);
9 Likes

Looks great, but the selection won’t change and I can’t find ANY decent documentation on EditorStyles.radioButton. Do I need to add a handler or something?

EditorStyles is just a regular GUIStyle but it’s themed with the editor art, it does not effect input at all. My guess is that you copied and pasted the code above without looking at how it works.

If you notice the first argument is a 0 and GUILayout.SelectionGrid returns an int. Try saving that value and sending it back in.

http://docs.unity3d.com/ScriptReference/GUILayout.SelectionGrid.html

I thought I would chime in since this is currently the first thing that comes up on google when you enter “Radio Button Unity”, and the answers here are outdated.

You should use a ToggleGroup component, and uncheck the “Allow Switch Off” property. Then on any arbitrary Toggle components you set the toggle group to the above. Now you’ve got a radio group plug and play!

https://docs.unity3d.com/Manual/script-ToggleGroup.html
https://docs.unity3d.com/ScriptReference/UI.Toggle.html

3 Likes

this answer is true if you are using the new unity GUI system (which you should be, if it’s an option)
but sometimes it’s not an option, like if you’re building editor windows.

I think this is exactly what you are looking for:

int selected = 0;
public void OnGUI()
    {
string[] options = new string[] { "  version 1", "  version 2" };
selected = GUILayout.SelectionGrid(selected, options, 1, EditorStyles.radioButton);
if (selected == 0)
                {
                    Debug,Log("Version 1 is selected");
                }
else if (selected == 1)
                {
                    Debug,Log("Version 2 is selected");
                }
}
4 Likes

Fantastic, thank you