Unity C# Basics — Tip Calculator

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

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Why My Future is Serverless in the Microsoft Cloud

CS373 Fall 2021: Thomas Connor Thompson

How I Taught Myself to Print Gold and Launch A Jewelry Line

Static and dynamic libraries in C

Enjoying the Ride

Next! — A quick guide to loading scenes in Unity

How to Build a Car Racing Game in AR in 15 Minutes or Less

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Ryan McCoach

Ryan McCoach

More from Medium

C# LINQ — “Distinct”

Overloading methods in C# & Unity

Animating Zombies: Root Transforms

Spawning objects in unity without the clutter