Trying to detect typing into a text field for an editor extension, but it returns an empty string sometimes which makes it really hard to detect when the text field is empty:
private void OnGUI()
{
var itemName = EditorGUILayout.TextField("Item Name", "");
Debug.Log(itemName);
}
This outputs the typed input correctly but then the method gets called another four times and the itemName is empty.
When typing “asdf” for example, console output looks like:
asdf
-empty line-
-empty line-
-empty line-
-empty line-
What am I missing?
private string itemName;
private void OnGUI()
{
itemName = EditorGUILayout.TextField("Item Name", itemName);
Debug.Log(itemName);
}
The problem is that you are declaring itemName inside OnGUI, so it’s discarded the instant OnGUI ends. It needs to be a global variable.
Are you doing this in an actual editor GUI window or in a game window? If I do this in a script attached to a normal game object and run I get the same behavior. Are you sure you don’t want GUILayout.TextField
instead of EditorGUILayout.TextField
?
And as Eric said, you also need to declare itemName
in the class or globally rather than locally in the function, e.g…
public class TriggerTest : MonoBehaviour {
string itemName = "";
void OnGUI()
{
itemName = GUILayout.TextField(itemName);
}
}
Otherwise you’ll lose the value each time OnGUI is called.