1
\$\begingroup\$

I've been trying to make a custom editor window in Unity and I needed to make an "add TextField" button. When I add a TextField directly (without requiring a button), it works. When I put it under if(GUI.Button()) it does not show up. Here's my code:

private static List<string> s = new List<string>();
private void OnGUI()
{
        
    if (GUI.Button("+");)
    {   
        s.Add(GUI.TextField(new Rect(0,50,Screen.width,20),"field"));
    }
}
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

Unity’s IMGUI is a really strange beast, and you seem to have a basic misunderstanding of how it works. This is a method that basically gets called over and over and over, and each control you want to appear needs to be called every time. However, GUI.Button only returns true once, when clicked. So you need to display the text fields outside the if statement, and inside the if statement is just where you “remember” to show it.

From what I can see, it seems like you want the plus button to add a new text box with the contents set to “field” each time it’s clicked, so here’s my attempt at that:

private static List<string> s = new List<string>();
private void OnGUI()
{
    if (GUILayout.Button("+"))
    {   
        s.Add("field");
    }
    for (int i = 0; i < s.Count; i++) {
        s[i] = GUILayout.TextField(s[i]);
    }
}

(From memory; pardon any compiler errors)

Note how I also used GUILayout instead of just GUI so I don’t need to specify the rect of each control.

\$\endgroup\$
1
  • \$\begingroup\$ Yeah, i have not much experience with it. Thx :D But, i knew about "GUILayout", it's just that i need to place things in my way ^^. \$\endgroup\$
    – TensaDev
    Jan 12, 2021 at 13:42

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .