Because I had a hard time getting this figured out and didn’t find a whole lot of help anywhere on the internet, I’m posting this here with hopes that others may find it useful.
Here’s how I set up my focusable text fields (using c#):
using UnityEngine;
using System.Collections;
public class FocusTextFieldExample : MonoBehaviour {
//Set up holder variable for the contents of your text field.
private string firstNameField;
//Set up variable to hold the default value to revert back to upon losing focus while empty
public string firstNameFieldDefault = "Enter First Name...";
//Same stuff with a second set of variables
private string lastNameField;
public string lastNameFieldDefault = "Enter Last Name...";
void Awake () {
//You probably want to initialize your textfield text with the default text
firstNameField = firstNameFieldDefault;
lastNameField = lastNameFieldDefault;
}
void OnGUI () {
//Optionally label your fields
GUILayout.Label("First Name: ");
//Run the custom FocusableTextField function created below
//Make sure to plug in all 4 necessary variables
FocusableTextField(firstNameField, out firstNameField, firstNameFieldDefault, "FirstNameField");
//Same thing but with the second set of variables
GUILayout.Label("Last Name: ");
FocusableTextField(lastNameField, out lastNameField, lastNameFieldDefault, "LastNameField");
}
//Custom FocusableTextField function
void FocusableTextField(string currentTextIn, out string currentTextOut, string defaultText, string fieldName) {
//Give the text-field a nametag
GUI.SetNextControlName(fieldName);
//Create the text-field
currentTextOut = GUILayout.TextField(currentTextIn);
//Check if the text-field has gained focus
if (GUI.GetNameOfFocusedControl() == fieldName currentTextOut == defaultText) {
currentTextOut = "";
}
//Otherwise, check if the text-field lost focus
else if (GUI.GetNameOfFocusedControl() != fieldName currentTextOut == "") {
currentTextOut = defaultText;
}
}
}