If and Else Function of C# Unity

Jacob Jones
2 min readJun 14, 2021

--

Let’s go over the If and Else functions that we can use in unity. The example that we are going to do is going to also include the Random.Range function. We are going to see if a person passed or failed their quiz! If you need help see my previous article on the Random function!

In the void Update section, lets begin with writing the if statement. So if they quiz average is greater than or equal to 70 then we pass. To write this out type, “if (quizAverage >= 70)”. Once we have this written, we need to tell the code what we want it to do based on our parameters so lets add {} brackets. If you just type the first bracket and hit enter it will set you up to write your next line!

Lets add in a Debug.Log message now! In-between the {} brackets lets write out our message. Debug.Log(“Congratulations class, todays average was ” + quizAverage + “and we have passed!”; Now if the average is higher than 70 then in the console it will pass our message! However, if the average ends up being lower than a 70 then nothing is going to happen, so lets fix that with an else statement!

After we establish the if statement, an else will answer to the opposite. In this case it is, if we score less than a 70. Write, else and then enter to write your Debug.Log message. Now lets test it out!

A good lesson to take from this as well is to make sure you are double checking your work! If you noticed, in our message I misspelled congratulations! I also forgot to add a space in our failure message! Its always good to learn from your mistakes to prevent them in the future. Hope you enjoyed my how to, stay professional!

--

--