Unity C# Basics — Weapon Switch

Ryan McCoach
3 min readAug 12, 2021

In this C# mini project, the goal is to use the Left and Right arrow keys to cycle through different “weapons”. The fundamental concept used in this project is Switch statements.

The Code Breakdown

We are declare a few variables…

  1. _weapon ID = is the number that will represent a certain number
  2. _weaponName = is the name corresponding with the Weapon ID.
  3. _cube = is the renderer of the gameObject that we can change the color of to represent a different weapon.

Now, lets initialize the Weapon ID and Weapon Name. We will also need to get the Renderer component and assign it the Cube variable.

In the Update, we are going to use the Left Arrow key to cycle backwards through the weapons and the Right Arrow key to cycle forward. First, we are going to focus on changing the Weapon ID using the Right Arrow key. Each time we hit the Right Arrow key, we set the Weapon ID to the current Weapon ID plus 1. For example…

At the Start the Weapon ID = 0, we hit the Right Arrow key this now makes it (0 + 1) = 1. Now we use the remainder operator (%), which is a modulus operator and it gives you the reminder of a / b. For example…

9 % 2 = 1 because 2 x 4 = 8 and 9–8 = 1 ← which is the remainder. Since we are dividing a smaller number by a larger number it will just return the smaller number. For example…

1%9 = 1

2%9 = 2

3% = 3 etc…

So 1%3 = 1. When we hit the Right Arrow key again, (1 + 1) = 2 % 3 = 2. When hit the Right Arrow key again, (2 + 1) = 3 % 3 = 0 because 3 goes into 3–1 time with no remainder so 0.

Looking at using the Left Arrow key, we are just reversing the process. This can get confusing but the idea for this type of modulus cycling is when you are cycling forward…

(current selection value + 1) % total amount of selections

and cycling backwards would be…

(current select value + (total amount of selections -1)) % total amount of selections.

Now that we are cycling through our Weapon ID numbers, we can implement our Switch statements. Switch statements are great for replacing multiple IF, ELSE IF, ELSE statements. The image shows how syntax of Switch statements and make sure to end each case with a break; to allow the program to move onto the next case.

and would be the same as saying…

if (_weaponID == 0)

does this

else if (_weapon == 1)

does this

else if (_weapon == 2)

does this

Just image if the game had over 20 weapons…that would be a lot of IF statements and that is the pro of using Switch statements. It simplifies the code and makes it easier to read.

Hopefully this was helpful! Cheers!

--

--