Unity C# Basics — Tip Calculator

Ryan McCoach
3 min readAug 10, 2021

--

This article will cover a few Unity C# basics in a mini-project on creating a basic tip calculator in Unity’s Inspector.

Making Comments

Let’s get into the script and cover how to make comments or pseudocode. If you want to make a 1 line comment you simply need to use //Comment.

If you have more than a line for comment you can use /*Comment*/ around what you want to make a comment.

Variable Types — Private or Public

Best practices for formatting variables is using camel case, which is making the first word lower case and all of the following words will be upper case.

camelCaseExample

NotCamelCaseExample

notCamelcaseExample

Another best practice in formatting variables is using an underscore before a Private variable name and a Public variable will be without the underscore.

_privateVariable

publicVariable

Public variables will show up in the Unity Inspector which can be modified and can be accessed by other scripts.

Private variables will not show up in the Unity Inspector and cannot be accessed by other scripts.

You mostly want to keep variables Private, but still want to show it up in the Unity Inspector so you can modify on the fly, you can add a SerializedField attribute. This will keep the variable private, but it will appear in the Inspector.

For the Tip Calculator we are going to keep the variables private with a SerializedField.

The Code Breakdown

The first thing we need to figure out when the user puts in the bill amount and the tip percentage they want will be how much the tip will be. This will require multiple the bill total by the tip percentage, which gives you the tip amount. We will only calculate this when we press the Space Bar.

The tip amount is to the thousandths and we need to to only go to the hundredths. So, we are going to use the rounding math function by multiplying it by 100 and dividing that rounded integer by 100.

We need to add the tip amount to the bill amount to get the total amount. Again, we want to make sure it is rounded to the nearest hundredths, so we will use the same trick as before.

There you go a very basic tip calculator.

The Code

--

--

No responses yet