Unity C# Basics — Catch the Rain
This mini project will focus on implementing the use of Methods to make a game where the player must move left and right to catch the “Rain” falling and prevent them from hitting the ground. Each rain drop will be worth different points when caught and if they hit the ground they cost different damage amounts.
Lets talk about Methods; what they are and how we can use them. Methods are bits of code that each contains everything necessary to execute only one aspect of the desired functionality. It is helps make the code easier to read and easier to debug. The reason is because it compartmentalizes bits of the code that focuses on one behavior.
You can see the example above that the Method is handling the player’s movement and is being called in the Update, which is also a Method, so it is always be checked since it has inputs. If there was a bug in the movement, I can easily debug because the movement code is encapsulated in the method so the bug would most likely be there.
Syntax for a method is either start with private or public void (if you just put void it will default to private) and this determines if it is only accessible on that script alone (private) or can be accessed by other scripts (public). The void is followed with the name of the Method.
Using parameters, you can make Methods more flexible. This Method is on the Player script and will add a certain amount of points depending on what Raindrop was caught and a certain amount of health to be taken away if it hits the ground. The Player’s points/health is stored in a global variable and in both the AddPoints & TakeDamage method I will need an INT parameter with some name (value). This INT parameter (value) will be added to the player’s score or taken from the player’s score.
On the the Raindrop’s script, when it collides with the Player and depending on what Raindrop it was will determine the INT value that will be passed in the AddPoints method. I am able to access this method on the Player’s script because the method was public.
Method parameters can be any variable type (string, float, and bool) and they can also be different structures and classes (i.e. GameObject). In the example, the parameter is a Color structure and and I using it to assign the color for the raindrop and rain light.
Methods can return values (ints, float, string, bool) as demonstrate above. It is a bool Method that is checking to see if the Player’s health is less than 1. If it is than it will return TRUE and anything else will FALSE
Then I can use it in logic just like a variable.
This doesn’t go over all of the code but gives you an idea on how you can use methods to clean it up and make it more efficient. Cheers!