- Home /
Default text / Already written text on GUI Text Field.
How can I have a text already written on a text field at the very start of the game?
Like, when I start the scene, there will already be text written on the text field, but the player can still edit it if they wish to do so.
Here is the code I'm using for the text field:
void OnGUI() {
Rect r = new Rect(Screen.width/15,Screen.height/3.5f,width,height);
GUILayout.BeginArea(r, new GUIStyle("box"));
text = GUILayout.TextField(text, layout);
}
Thanks!
Answer by Starwalker · Jul 14, 2014 at 08:54 PM
Try this:
public string text = "Hello World";
void OnGUI() {
Rect r = new Rect(Screen.width/15,Screen.height/3.5f,width,height);
GUILayout.BeginArea(r, new GUIStyle("box"));
text = GUILayout.TextField(text,25, layout);
}
Above code is from GUILayout Reference here: http://docs.unity3d.com/ScriptReference/GUILayout.TextField.html
If it works then its probably because the 2nd parameter is required to tell that there is already text in the textfield and not blank it out.
Converted your comment to an answer @Starwalker
...and it works because when you declare the variable [text] you gave it a value of "Hello World" ins$$anonymous$$d of leaving it empty. The 2nd parameter you passed in GUILayout.TextField(text, 25, layout) is to make this text-field only allow a maximum length of 25 characters in the string.