Class Functions
So far, we've added variables to a script we've created. Those variables save information about that 'thing', like the health of a player.
Our script doesn't have to just contain data though, it also might need to include things that the script does. This is where class functions come in.
What Are Functions?
Functions are essentially a command that we can call to tell the class to do something. This might be, for example, to move around, or to take damage, for a real-time game. The function may need some additional information to run, and these are called arguments.
Functions also might return something when they are called. For example, you might use a function to calculate the damage of an attack by multiplying some numbers together. This is known as the function's return type. If a function doesn't return anything, we consider it a void type.
Defining Class Functions
To add a function in a class, we need to define it. This means describing what it does, what it returns, what arguments it requires etc.
Class functions are defined inside our class (as in, the curly braces of our class) but not inside the Start()
or Update()
messages.
We are going to make a class function that will add two numbers together. This would like:
public class Player : MonoBehaviour
{
int AddTwoNumbers(int a, int b)
{
return a + b;
}
//....etc.
First, we are defining the class's return type. In this case, we are defining it as an integer, meaning this function will give us an integer back.
Next, we name our function. In this case, it's called AddTwoNumbers
.
Inside the parenthesis, we need to add any parameters we need, essentially the arguments that are required for the function to work. In this case we have two parameters defined; an integer called a
and an integer called b
, separated by commas.
Inside some braces, we define what the function is going to do. Our function here is very simple, we are going to return the sum of a + b.
If we didn't want our class function to have a return type, we would simply type void as the return type. This means the function does not give us any data, it just does something. An example of this might be if we wanted to make a function to make a character jump. We don't need any additional information afterwards.
void Jump()
{
//Put some code here to make the player jump, e.g. Rigidbody's add force.
}
We might also want this class function to be called from outside this class. This is particularly common with a player's movement and controls generally, as you might want them to be called from a UI button. We can make a function accessible from outside this class by adding the word public
before the return type.
void Jump()
{
//Put some code here to make the player jump, e.g. Rigidbody's add force.
}
Examples of Function Declarations
Here are some examples of functions you might define in a game:
float DamagePerSecond(float attackDamage, float attackSpeed)
{
return attackDamage * attackSpeed;
}
This function has the return type float
, requires two arguments, both of type float
, and returns the sum of attackDamage
multiplied by attackSpeed
.
bool CanPlayerRevive(bool alive, int numberOfTurnsDowned)
{
if (alive)
{
return false;
}
else if (!alive && numberOfTurnsDowned < 3)
{
return true;
}
else
{
return false;
}
}
This function returns a bool
and is used to check whether a character in an RPG can be revived or not. Our parameters are a bool
determining if the character is alive, and an int
considering how long we have been downed for. We can then return either a true or false depending on whether the character can be revived or not, based on checking those arguments.
Summary Attribute
Much like the Unity Editor tooltips we added, it can be useful to use some system to explain to other people what our functions do. This might not always be obvious, particularly to less experienced programmers. We can use the three-slash comment and the <summary>
tag to do this. It will allow you to describe what a function does, and then when you hover over that function, it will give you a tooltip.
/// <summary>
/// Adds two numbers together and returns them.
/// </summary>
int AddTwoNumbers(int a, int b)
{
return a + b;
}
Here, you can see what happens if I hover my mouse over that function:

Calling Class Functions
Once we have declared our class's functions, we can then use those functions. Using a function in a script is known as calling.
To call a function, we simply write the name of the class, followed by parenthesis, and then add arguments in the parenthesis where necessary:
public class Player : MonoBehaviour
{
//Defining the class function.
void Jump()
{
//Do some code to make my player jump, e.g. rb.AddForce()...
}
void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
//calling the class function.
Jump();
}
}
}
If our function has a return type, we can assign a variable to its return value at runtime:
public class Player : MonoBehaviour
{
int sum;
int AddTwoNumbers(int a, int b)
{
return a + b;
}
void Start()
{
sum = AddTwoNumbers(1, 2);
}
}
Conclusion
Functions allow us to define what a class does.
Functions can return some information/data, or simply just execute some code.
You can use the <summary> tag explain what a function does.
If we want a function to be callable outside the of the class it is defined, it needs to have the public
access modifier.
Making all of your player's actions as public class functions allows things outside of the class to control your player, like UI buttons.
Reference Script
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Roller : MonoBehaviour
{
Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void Update()
{
if (Input.GetKey(KeyCode.W)) { MoveForward(); }
if (Input.GetKey(KeyCode.S)) { MoveBackward(); }
if (Input.GetKey(KeyCode.A)) { MoveLeft(); }
if (Input.GetKey(KeyCode.D)) { MoveRight(); }
}
/// <summary>
/// Used to move the object forwards, no argument needed.
/// </summary>
public void MoveForward()
{
rb.AddForce(0, 0, 1);
}
/// <summary>
/// Used to move the object backwards, no argument needed.
/// </summary>
public void MoveBackward()
{
rb.AddForce(0, 0, -1);
}
/// <summary>
/// Used to move the object left, no argument needed.
/// </summary>
public void MoveLeft()
{
rb.AddForce(-1, 0, 0);
}
/// <summary>
/// Used to move the object right, no argument needed.
/// </summary>
public void MoveRight()
{
rb.AddForce(1, 0, 0);
}
//--------------------------Examples of potential functions.--------------------------------------//
/// <summary>
/// Adds two numbers together and returns them.
/// </summary>
int AddTwoNumbers(int a, int b)
{
return a + b;
}
/// <summary>
/// Calculate damage per second on an attack.
/// </summary>
float DamagePerSecond(float attackDamage, float attackSpeed)
{
return attackDamage * attackSpeed;
}
/// <summary>
/// Logs that the game has begun in the console.
/// </summary>
void GameHasStarted()
{
Debug.Log("The game is running.");
}
/// <summary>
/// Checks whether a player can revive or not by checking if they are dead, and if so, how many turns for.
/// </summary>
bool CanPlayerRevive(bool alive, int numberOfTurnsDowned)
{
if (alive)
{
return false;
}
else if (!alive && numberOfTurnsDowned < 3)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// Combines a character's first and surname into a single string.
/// </summary>
string CombineNames (string firstName, string Surname)
{
return firstName + " " + Surname;
}
}
Last updated