- Home /
How to output variable in textfield?
What I'm trying to do is a textfield, for max players for multiplayer game. How can I make it so he can only write numbers, and so the output in textfield goes to a variable? I'm stuck on this, anyone with a better idea on how to do this is very appreciated. Thanks in advance.
Why do you need a text field, have him enter numbers only, and then parse his input? - why not just use a numeric field?
If you insist on a text field, use a regular expression. Something like @"[0-9]" - look at the Regex drawer they have as an example property drawer http://blogs.unity3d.com/2012/09/07/property-drawers-in-unity-4/
Crap I thought there was something like a GUI.FloatField
- there isn't. There is EditorGUI.FloatField
but I think you want it at runtime... like this.
Answer by vexe · Mar 17, 2014 at 03:59 PM
Alright tried this, it works - I wrote it as an Editor, but the idea is applicable in GUI code too... The key elements are: 1- the regular expression. 2- the int.TryParse function to turn the string into an int.
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEngine;
[CustomEditor(typeof(Test))]
public class TestEditor : Editor
{
string strValue = "";
int intValue;
Regex numbers = new Regex(@"^\s*[0-9]*$"); // this means: anything that 'starts' with any number of spaces followed by any number of digits between 0-9. the $ signifies the end, the ^ is the start. you could use \d instead of [0-9]
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
GUILayout.BeginHorizontal();
{
EditorGUILayout.PrefixLabel("StringValue");
string newValue = GUILayout.TextField(strValue);
if (numbers.IsMatch(newValue)) {
strValue = newValue;
int.TryParse(strValue, out intValue);
}
}
GUILayout.EndHorizontal();
GUILayout.Label(intValue.ToString());
}
}
OH $$anonymous$$Y GOD I FORGOT I HAD THE QUESTION UP!! I'm so sorry I feel bad >.<. Thank you so much! I havent tried it yet since I only use javascript, but I'll try and use your method. Thank you again and I'm so sorry :/!
Your answer
![](https://koobas.hobune.stream/wayback/20220613140451im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
How to make a variable int having data of a textfield? 1 Answer
Display Playerpref string in GUI.TextField. 2 Answers
Display additional text before the variable that the user is editing in a GUI Text Field 1 Answer
Communication between objects and other scripts, variables and properties 1 Answer
Rewind/Play animations on demand. 1 Answer