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.
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());
}
}