TextField Int

Hi!

I am working on allowing the player to make their own resolution and I need a text field that you can enter the numbers you want your resolution to be.

Here is a VERY simple script I made just to showcase:

    int resX = 1000;
	int resY = 1000;

	void OnGUI () {
		resX = GUI.TextField(new Rect(10, 10, 300, 25), resX, 4);

		resY = GUI.TextField(new Rect(10, 40, 300, 25), resY, 4);

		if(GUI.Button(new Rect(10, 70, 300, 25), "Apply")){
			Screen.SetResolution(resX, resY, false);
		}
	}

If you know what to do, please tell me in C#. Thanks

You need to parse the string to an integer using int.Parse or int.TryParse. The difference is that TryParse will make sure the given string is actually an integer, while Parse doesn’t.

 if(GUI.Button(new Rect(10, 70, 300, 25), "Apply")){
    int xRes, yRes;
    if(int.TryParse(resX,out xRes) && int.TryParse(resY, out yRes)){
        Screen.SetResolution(xRes, yRes, false);
    }
}

EDIT:
I just realized you declare your resX and resY as ints. They must be strings, because TextField deals with text, not numbers.

In order to make the textfields accept only digits, a simple (though maybe not the most efficient) way is to use Regular Expressions.

string resX="1000";
string resY="1000";
System.Text.RegularExpressions.Regex pattern = new System.Text.RegularExpressions.Regex("(^\\d+$)");
void OnGUI () {
    string temp;
    temp = GUI.TextField(new Rect(10, 10, 300, 25), resX, 4);
    if(pattern.IsMatch(temp) || temp.Length == 0)
        resX = temp;

    temp = GUI.TextField(new Rect(10, 40, 300, 25), resY, 4);
    if(pattern.IsMatch(temp) || temp.Length == 0)
        resY = temp; 

    if(GUI.Button(new Rect(10, 70, 300, 25), "Apply")){
        Screen.SetResolution(int.Parse(resX), int.Parse(resY), false);
    }
}

Hi,

I Think you’re trying input only the numbers, it can be solvable using RegEx.

using System.Text.RegularExpressions; // needed for Regex

private string resX = "";
void OnGUI()
{
   resX = GUI.TextField(new Rect(10, 10, 300, 25), resX, 4);
   resX = Regex.Replace(resX , "[^0-9]", "");
}

And parse resX as int.