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

Creating a text field is pretty simple with Unity GUI, there's two options:

  1. GUI.TextField(...)
  2. GUILayout.TextField(...)

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

that looks nice but it looks like it could be heavy?