Calculating Averages with C# in Unity

David Little
3 min readApr 14, 2021

--

For this tutorial, we’ll be calculating averages. Our scenario is that we have some quiz scores and we want the average score. Ground rules, the quiz scores need to be generated by the script and the values that are generated need to be random. The results should be printed in the Console in Unity.

First, as, always, the variables. Just like the Tip Calculator, you can do these a few different ways. It just depends on how much you want the code to be available for updating via the variables or through updating the math in the body of the script.

There are the quiz grades…

Which, when I first did this were all on their own separate lines with public and float being stated each time. Then later in a straight line as you see here. It works, it takes less time to type, it’s more efficient and it just looks better as a single line.

Next are the quizSum, nQuizes, and quizAverage variables.

While it is possible to do all of these as local variables, they would not be accessible through the Unity editor. I wanted to try and make it possible to modify all of the variables from there. Though in post I will say that did not make much sense for the Sum and Average as their function needs to be defined later. The script does produce the same results either way.

Then we need the random values for the quizzes. This was done with Random.Range where you tell the script what the lower and upper limits, inclusive, are to be for the range of choices.

Initially, I could not get Random.Range to work. For a while, and successfully, I was using Random.value, which would return a value between 0.0 and 1.0. I would then multiply the quizSum by 100 to get my quiz scores between 0 and 100 when dived for the average. I find that Random.Value at least required less typing since I did not have to repeat the range of values for each quiz variable.

We then set up the calculations for the Sum and the average.

And, finally Debug.Log for the results, which, again, there are a few ways that I found to do this. Remembering of course that we want these results to be limited to two decimal places. You could use Mathf.Round to round and two different applications of ToString. Here is a comparison.

quizAverage by itself here would require the use of…

Ultimately, this is the final form of the script that I used.

This was a fun exercise for me in exploring the different ways that the same result can be obtained from variations in the writing of the code itself.

--

--

No responses yet