Build a math game in Unity in 5 minutes
Objective: Make a math game quick.
With one script, one button, one input field, two text’s, and two methods we can create a workable math game. To start Unity we will create a Input Field.
Create four text objects. I put all text objects as child to a empty to keep organized.
Space them out a little bit.
Reason for each text being separate is to allow us to change the numbers later on.
Next is to create a button.
Create a C# script and grab the TMPro library.
We need variables for some of the text objects, the input field, and int’s to set the number text.
Create a method that will randomize numbers for the numbers to get added up. This method will also set the correctText and answerField to be empty. Then assign the correctAnswer variable to equal firstRandNum + secondRandNum.
Create another method that will take in the user input, change it to an int using int.Parse(). Use an if statement to see if the user input is equal to the correctAnswer. If it is, change isCorrectText to say ‘Correct’ and if not, change isCorrectText to say “Answer is incorrect, the answer is{correctAnswer}.
In start call the RandomNumbers() method to start the game correctly. I also set the isCorrectText to be empty.
Back in Unity assign the script to an object and drop in the Input Field, 1st number text, 2nd number text.
Last two things that need to be done is on the Input Field object, add an event in On End Edit. Drop in the object that has the script and select the Check Answer Method.
And on the Button, add an event in OnClick event and drop in the object again and select the RandomNumbers method.
With that we have a working Math game now!
Thank you for reading! Have a wonderful day!