How to Use Random Variables!

Jacob Jones
3 min readJun 13, 2021

If you want to know how to randomly generate numbers in a Unity script then you came to the right place! We will be creating a way to calculate random test scores! Lets looks at our script!

To begin we want create floats of 5 different quizzes that we can use in our equation. If we just use a comma, we can just make one line of code instead of 5 to save ourselves time! If your are not familiar with a float, it is a variable that is specific to decimals.

Now we need to create the code that will randomly generate numbers between 0 and 100! First you need to type the name of the quiz1 = Random.Range(0, 100). This is telling the code that we want to generate a random whole number with a range of 0 and 100. If you put an f after each digit, then it will generate a random number between 0 and 100 to include decimals. See above for reference, once you have written the first one, continue 5 more lines of code!

Lets create the actual equation to calculate the average of 5 randomly generated quiz scores! First, go ahead and create another variable, this one is going to be a public float named as quizAverage. To make the average, we need to add up all the quiz scores, and then divide them by 5. Do this by typing, quizAverage = ((quiz1 + quiz2 + quiz3 + quiz4 + quiz5) / 5);. We need the first set of parenthesis for the actual equation, and then the next set to tell the code to add first before we divide.

Finally lets add a Debug.Log so that we are able to check our work in the console of Unity! Write, “Debug.Log(“Todays class average is “ + quizAverage + “!”);” underneath the quizAverage equation that we created. You can write it in your own words, just make sure the text of what you want to say is in quotes! Finally lets save our script, drag and drop it onto any asset in our Unity project and press play! (You can even add it to the main camera if you want)

Congratulations, hope you have learned something to help you in the creation of your next project!

--

--