Unity Editor: Required text or number input

When you create a custom inspector or editor and have to provide an input field that the user has to fill out (even though a rare requirement), you should ideally signal the user just that, both for added usability and to make sure that the user is filling out the required fields to proceed.

For that I'm going to show you both how to color a text or number input red when the required conditions haven't been met and also how doing so will prevent the rest of your form to be completed without filling the required fields first.

The most common scenarios for this is if a string shouldn't be empty or shouldn't contain certain characters or if a number input is out of range (though for this you can also just set the min and max value of a number input to prevent the user from even entering values outside of it).

Let's have a look at a function that displays a string input and recolors it into red if the string is empty:

/// <summary>
/// Displays an input field that shows, whether the input is invalid (empty) or not.
/// </summary>
public static string DrawRequiredInputField (string input)
  //cache default GUI color
  Color defColor = GUI.backgroundColor;

  bool isInvalid = string.IsNullOrEmpty(input);
  if (isInvalid) GUI.backgroundColor = new Color (1f, 0.67f, 0.7f);

  //if the given value is null, set it to an empty string to prevent errors when putting it in the TextField
  if (input == null) input = ""

  //create the actual text field
  string newInput = GUILayout.TextField(input);

  //reset GUI color
  GUI.backgroundColor = defColor;

  //prevent starting with a whitespace
  if (newInput.Length == 1 && newInput == " ") newInput = string.Empty;

  return newInput;

We could've also just assigned Color.red to the GUI.backgroundColor, but that color might be a bit too bright, especially when using Unity's professional theme (dark mode).

Now we only need to incorporate this function in a place where we would normally just call GUILayout.TextField() to draw the default input field, only now with the added check for whether the input value is inside the domain of validity (aren't abstract descriptions something beautiful =]).

newName = DrawRequiredInputField(name);
if (string.IsNullOrEmpty(newName)) isInvalid = true;

With this isInvalid variable, we can now prevent anything in the inspector/editor from happening that relies on that input being set, thus achieved our desired behavior.

Fri May 08 2020