Gamieon is a one-developer part-time studio focused on creating video games for the desktop and mobile platforms. Since 2010 Gamieon has developed and released six games as well as six more prototypes. Including beta distributions, Gamieon's products have netted a combined 300,000 downloads! Below this bio are images from all my games and prototypes. Check them out and don't forget to follow me on Twitter @[Gamieon](members:gamieon:321769)

Report RSS A way to do a numeric GUI.TextField in Unity in C#

Posted by on

Unity developers are familiar with

csharp code:
myText = GUI.TextField(myRect, myText);

But if you want a text field that only accepts numeric input, then you could accomplish it with some Regex filtering:

csharp code:
using System.Text.RegularExpressions;
...
myText = Regex.Replace(GUI.TextField(myRect, myText), "[^.0-9]", "");

Now suppose you wanted to contain it all in a function. The first thing that comes to mind is:

csharp code:
int NumberField(Rect r, int n)
{
   string result = Regex.Replace(GUI.TextField(r, n.ToString()), "[^.0-9]", "");
   return System.Convert.ToInt32(result);
}

Looks fine on the surface, but there's a glaring problem: It can't handle empty inputs. If you want to treat 0 as an empty input and change the function handle to it accordingly, you could do that. I chose to go this route:

csharp code:
int? NumberField(Rect r, int? n)
{
   string result = Regex.Replace(GUI.TextField(r, n.HasValue ? n.Value.ToString() : ""), "[^.0-9]", "");
   if (string.IsNullOrEmpty(result))
   {
      return null;
   }
   else
   {
      return System.Convert.ToInt32(result);
   }
}

Rather than processing an integer, I process a nullable integer. This way I can discern valid from invalid input without using sentinel values.

(Credit to Labs.kaliko.com for the expression ... and a special thanks to the author for actually including the namespace in their code snippet! )

Check out my homepage and social feeds

And my projects!

Post a comment

Your comment will be anonymous unless you join the community. Or sign in with your social account: