- Home /
equation game question need help
Hi,
I make a simple Unity3D math game script that user must enter correct answer for the math problem given. This is the script I used. I just attached this scrip to an Empty game object on a blank scene. Try this to figure out what I get.
#pragma strict
var a : int; //Define variable a as int
var b : int; //Define variable b as int
var c : int; //Define variable c as int
var stringAnswer : String; //Define the answer as string input
var numAnswer : int; //Define answer in numeric as int
function Start()
{
a = Random.Range(0, 9); //Get random value for a
b = Random.Range(0, 9); //Get random value for b
c = a + b; // c = a + b
}
function OnGUI()
{
GUI.Box(Rect(Screen.width/2 - 200, Screen.height/2 - 5, 400, 40), a + " + " + b + " = "); //Create a box show the equation
stringAnswer = GUI.TextField(Rect(Screen.width/2 + 30, Screen.height/2, 40, 30), stringAnswer, 2); //Create a text field that player input the answer, wether it numeric or text.
numAnswer = int.Parse(stringAnswer); //Convert the string answer to int value
if(numAnswer == c) //Compare the int value of answer with c
{
print("Answer is Correct !!"); //If answer is equal c, tell in terminal that the answer is correct. In future will be a GUI text.
}
else
{
print("Answer is Wrong !!"); //If answer is not equal c, tell in terminal that the answer is wrong. In future will be a GUI text.
}
}
then when I run, I get this error message :
FormatException: Input string was not in the correct format System.Int32.Parse (System.String s) test.OnGUI () (at Assets/test.js:20)
That is error in parsing text to integer value.
I use Unity3D v.3.5.5f3 on Windows7 64.
Are there someone could help me correcting this script?
Thank You very much for Your help.
The problem is that you are not checking that the inputted string is of the correct format before attempting to parse it. When the field is initialised, it will contain an empty string- which is an invalid format, because it cannot be converted into an integer! I recommend surrounding the 'int.Parse' function with a try-catch block, and handling the error manually. I'm not entirely certain of the correct syntax for that in JavaScript, so you'll have to ask someone more knowledgeable than me.
Answer by Ashkan_gc · Jun 04, 2013 at 08:39 AM
Use the int.TryParse instead of Parse, If it returns true then it means it could parse the text.