- Home /
EditorGUILayout.TextField returning empty string
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?
Answer by vividhelix · Oct 25, 2013 at 04:33 PM
private string itemName;
private void OnGUI()
{
itemName = EditorGUILayout.TextField("Item Name", itemName);
Debug.Log(itemName);
}
Answer by Eric5h5 · Oct 25, 2013 at 04:32 PM
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.
Actually it's not discarded since I'm using it in the same method. The problem is as PTerto hinted what is the initialization value for the TextField - my initial code used the empty string while it should be using the previous value.
Answer by Dave-Carlile · Oct 25, 2013 at 04:34 PM
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.
The original question states this is for an editor extension. You are correct though, the solution is a combination of PTerto's and Eric's answers.
Your answer
Follow this Question
Related Questions
Fix editor TextField cursor alignment 1 Answer
How can I determine when user presses enter in an editor text field? 3 Answers
EditorGUILayout.ObjectField cannot be changed. 1 Answer
Recreate default editor look manually without base.OnInspectorGUI [UnityEditor] 2 Answers
Custom inspector difficulties creating a Box / Group like widget 1 Answer