- Home /
create a box that player can type in it ( only type numbers )
Hi How i can create a box that player can type in it ( only numbers ) ? thanks
Answer by jashan · Sep 06, 2010 at 09:10 AM
Creating a text field is pretty simple with Unity GUI, there's two options:
The difference is that with GUI, you have to manage positioning yourself, while GUILayout manages positioning for you, see also the GUI Layout Tutorial.
For allowing only numbers, there are a couple of possible solutions: One is trying to parse the string that was entered, and showing an error message to the user when that fails. One nice way of doing this (that avoids exceptions) is using Int32.TryParse(...). The disadvantage is that the user can enter a alphanumeric value which you probably don't want.
One solution that prevents entering non-digit characters can be found in the Unity forums: Only numbers in TextField. You could make this a little more elegant by using Char.IsDigit(...).
So that would give you (in C#; the example in the forum posting is UnityScript):
using UnityEngine; using System.Collections; using System.Text;
public class NumbersOnly : MonoBehaviour {
private string textFieldValue = "";
private StringBuilder textFieldTemp = null;
public void OnGUI() {
// NOTE: This creates a new StringBuilder every OnGUI-call which
// could be a problem in Unity iPhone because of Garbage Collection
// using stringVariable += c, however, would even be much worse!
textFieldTemp = new StringBuilder();
foreach (char c in textFieldValue) {
if (char.IsDigit(c)) {
textFieldTemp.Append(c);
}
}
textFieldValue = GUI.TextField(new Rect(10F, 10F, 100F, 20F),
textFieldTemp.ToString());
}
}
Hi,
I just try this method using StringBuilder. It's work fine except I cannot input the decimal separation then... that it the dot between the int and the fraction value.
Your answer
Follow this Question
Related Questions
create a box that player can type in it 1 Answer
"'UnityEngine.GUI.DoTextField' is inaccessible due to its protection level." 1 Answer
Having a GUILayout Window position immediately at screen center 5 Answers
Why can't I get my tooltip to show only when there is a tooltip set? 2 Answers
GUI.Window error. InvalidOperationException: Hashtable.Enumerator: snapshot out of sync. 0 Answers