Creating a tip calculator with C# in Unity
You think of unity, you think of games. Except that Unity can be used to create lots more than ‘just’ games. This example isn’t flashy but does show there are other uses, and, it’s a good training exercise with variables and math with C#.
We start by creating a new script in Unity and calling it TipCalculator. We then need to declare the variables. To focus on the variables and the math we’re going to set the total of the bill to $40 and the tip to 20%. However, I will discus options along the way. We also want the results of the calculation to show up in the Console in the Unity editor.
Lets begin with a series of comments laying out what we want.

Based on this we define the variables.

The tip can actually be handled a couple of ways. It’s determined by how you want to handle your math. As it is here, you will have to divide by 100 to get a percentage. You could also set your tip variable to 0.2 if you wanted to use multiplication of the bill by the tip amount. You could even set the tip variable to 1.2 to just multiply the bill by the tip to get the total answer in one operation.
We’ll actually handle most of our math in Console with Debug.Log. We’ll be adding the math into the very line of text that the script will send to the console. But first, the variables.

The math for this option looks like this…

The variable tipAmount is handled as a local variable and can be done in two ways. You can either make it equal to the bill times the tip/100, if you use tip = 20.0 or the bill times the tip if you use tip = 0.2. Those options look like this, respectively.

And the totalAmount is handled as a local variable as well.

I went with tip = 0.2 for my final usage here…

Using tipAMount you can also do this…

This exercise helps to show that there are many ways to get the same job done with code. It depends more on the knowledge of the programmer, their style, and what might be possible for the same code later on in a project. Usually, the more variables that you have defined the easier it will be to expand upon. If I had done all my number crunching and defining in the final stages, those would need to be reworked if something was to change. A lot more work than just modifying the variables. Right now it’s a tip calculator. Later it could be, or incorporated into, something much larger.