Functions are how we group commands together so that we can reuse them over and over in our programs. Functions will not run their commands until called.
Function Definition: This is how we make a new function. When naming functions start with a capitol letter. We start a function definition with the word “function”. Next we put a space and then the name. After that we put parenthesis. The function needs a body, which we block off with the set of curly brackets.
Example: function definition
void NameOfFunction ( )
commands you want the function to run when called.
Calling a function: When we call a function, we are telling it to run it’s commands. We can do this anywhere, and as many times, as we need to in our script. To call a function we just say it’s name followed by a set of parenthesis.
Example: of a function call
AnyFunction ( );
Arguments/Parameters: Arguments (or Parameters) are pieces of information a function needs to do it’s job. We define arguments in the parenthesis after the function name in the function definition. Arguments are variables – so you need to give them a type followed by a name. In the example below we have two arguments that can hold integers. This function adds the numbers together and prints the answer.
Example: a function with arguments
void AddNumbers (int number1, int number2)
Debug.Log(“Answer is: ” + number1 + number2);
Returning a value from a function: Sometimes we want the function to send us a value back. To do this we use the return command. In the example below the function will return a true or false value after applying an amount of damage to the player’s health. If the player has more that 0 health the function will return a value of true. Otherwise, it will return a value of false. It returns this value through its return type which is the bool before the word function in the example below.
Example: function returning a value
bool CheckForDeath(int damage)
health -= damage;
if(health >= 0)
Example: using a returned value from a function – in this function call we are sending 50 to CheckForDamage. CheckForDamage will return a value of true or false which will replace the function call. We call the function inside an if statement so we can check to see which value was returned.
if(CheckForDamage(50) == true)
print(“Player is alive”);
print(“Player is dead”);