C# Challenge - Difficulty Selector
Choose a difficulty by choosing a ID!
Another day, another small challenge to get back into coding!
Let’s take a look at todays task!
This problem can be solved in multiple ways, as every problem can! Keep it simple for the beginning, therefore, let’s use a ID system!
We need to implement four small things:
- A variable to set the ID for the difficulty
- A algorithm to execute the code matching the chosen ID
- A check if the space key was pressed
- If it was pressed, look up the ID and jump to the right part of the code to print out the right message
Creating the logic
I. The variable
The ID is a full number, so we should use a variable of type int. As we want to assign it inside the Inspector, simply add a [SerializeField] in front of the variable.
II. Checking for the key-press
A button press can happen at any time, so the right place for the check is inside void Update(), as it gets called every single frame.
III. The algorithm as switch-statement
As soon as we press the Space key on the keyboard, we want to check which number the difficultyID has and print out the corresponding difficulty level. We could do this with some if-statements. However, that would not be very good for the performance of the program, as Unity checks every single if statement whether it matches the number or not. Whereas in a switch-statement, Unity jumps directly to the correct ID and executes the code in it. Sure, this wouldn’t really matter in such a small program, but just think about having a program with 1000 if statements…
The following IDs will correspond the following difficulties:
- 0 = Easy
- 1 = Medium
- 2 = Hard
- Everything else is invalid
To print out the difficulty, we need Debug.Log().
That’s all we need to do! If we attach the script now to the Main Camera and run the application, we will see the following end result: