Custom Unity Dropdown

Example code for a custom inspector that presents a list of strings as dropdown. Good for if you absolutely need this field to be a string, but would want to restrict what the variable could be. Ideally you’d use enums but in my case, since it was a string I used to find GameObjects with, I needed it to be a string.

This consists of 2 parts:

  1. Your original c# class with the variable you want to select.
  2. An Editor class that customizes the inspector.

Unit.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Unit : MonoBehaviour {

  [HideInInspector] public string playerName;
  [HideInInspector] public GameObject player;


  // Use this for initialization
  void Start () {
  }
  
}

Editor/UnitEditor.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;

[CustomEditor(typeof(Unit))]
public class UnitEditor : Editor 
{
  string[] _choices = new [] { "Player1", "Player2" };
  int _choiceIndex = 0;

  public override void OnInspectorGUI()
  {
    Unit myTarget = (Unit)target;

    DrawDefaultInspector ();

    _choiceIndex = EditorGUILayout.Popup("Player", _choiceIndex, _choices);
    // Update the selected choice in the underlying object
    myTarget.playerName = _choices[_choiceIndex];
    myTarget.player = GameObject.Find (myTarget.playerName);

  }
}

Notes

  • The UnitEditor class has to be stored in a Editor folder
  • The UnitEditor class inherits from the base Editor class
  • The [CustomEditor(typeof(Unit))] flag tells Unity to use this inspector for the Unit class
  • Because we override OnInspectorGui, the inspector would normally be blank. We use DrawDefaultInspector() to redraw the original and then add our own. Custom Unity Dropdown
  • To avoid something like this where we have both the original fields and the new dropdown, we can use [HideInInspector] before our public variables to hide them from the Inspector
  • Unity Custom Inspector Tutorial: https://unity3d.com/learn/tutorials/topics/interface-essentials/building-custom-inspector?playlist=17117
  • EditorGUILayout.Popup reference: https://docs.unity3d.com/ScriptReference/EditorGUILayout.Popup.html
  • Related Unity Answers links:
    • http://answers.unity3d.com/questions/126562/drop-down-menu-in-custom-editor.html
    • http://answers.unity3d.com/questions/458987/dropdownlist-with-string-array-in-editor-inspector.html