Functions vs Methods
Today we are going to talk about functions and methods and the differences between them.
First we must distinguish if it is a private or public method. If it is private it can only be accessed by the class that we are currently in. If it is public it can be accessed by any other class as well.
When you call a method nothing is going to be called until that method is executed.
Methods are used to create concise bundles of code. You can create sections of code instead of placing it all in the update function for easier readability.
You can also add parameters to a method. A quick example is doing addition. Where int a and int b are the parameters required to call the Sum method.
Another good one is if your player has health and an enemy is causing damage to the player. So in this script we have a method damage with a parameter of damage amount. When Damage is called the damage amount is subtracted from the players overall health every time the space key is pressed, and when the players health reaches 0 the player is destroyed.
Next I created a program where a cube changes color when the space key is pressed and the color change is controlled within the function.
Next we will be working with return type functions, where you assign a function to a variable. We will look back at using the Sum that we had earlier.
Next we will be working with changing position of an object. Here’s a few options.
- transform.position= (new Vector3(0, 0, 0)); (for snapping back to the origin)
I are now creating a program that checks if the player is dead or not. When the space key is hit, the player will take damage at a random amount. If the player is dead (health less than 1), there will be a printout that the player has died. Once the player has died no negative health values can happen.
Next I worked with 3 cubes and gave them the player tag, and every game object tied to the tag would go into an array and each cube(tagged object) was randomly assigned it’s own unique color.
Next I created an array of 5 different positions and used a custom method to generate a random index. Then I used another custom method to set the position to that sub index.
I learned a lot about working with custom methods, parameters, and returns. I will have to work with these more in the future.