Selecting GameObjects with a generic ComboBox in Unity3d


Unity’s GUI System does not offer a Combo Box at the time of writing and I needed a ComboBox to select different objects of a certain MonoBehaviour type in my simulation. Based on the ComboBox from here (there are a number of variations) I came up with my quick’n’dirty ObjectComboBox.cs script. It is a generic class that takes any kind of UnityEngine.Object (or an extension of Object) as a type parameter. That means any MonoBehaviour, Transform, GameObject, Vector3, you name it.

I put together a simple demo-scene that you can download as a unitypackage below. Choosing a GameObject in the dropdown will hide the previously selected one and display the selected one.

Usage of ObjectComboBox is quite simple, first we need to instantiate a new ObjectComboBox, with a specific type (e.g. GameObject). We have to give it a Rect, an array of GameObjects and a GUIStyle of your choosing. I do this in the Start() method of my GUISandbox class.

_comboBox = new ObjectComboBox<GameObject>(new Rect(150, 100, 100, 20), list, listStyle);

To display the ObjectComboBox, all you have to do is call Show() in OnGui():

GameObject selected = _comboBox.SelectedItem;
//do something

The labels are generated automatically from the ToString() method so for custom MonoBehaviours, all you have to do is override ToString() to return what you want.

If you need more customization and want to define the GUIContent type yourself instead of having it generated via the ToString() method then the script could be adapted to require Objects implementing a certain Interface that has a function to return a GUIContent type to give Icons and whatnot. That means you can’t use it to pick basic UnityEngine types such as GameObject but for any class you define. You could, for instance define a class PickableGameObject that extends GameObject.  

Download the unity package here.

Sidenote: Unity will ship with a better GUI System, one day :)

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>