Functions

Functions are sets of code that can be run multiple times.

Parts of a Function

Let's look at the code for creating and calling a function:

Custom functions must be created outside of the Start() and Update() functions.

// Creating a simple function called MakeRed
public void MakeRed() {
    gameObject.GetComponent<Renderer>().material.color = new Color(1.0F, 0, 0, 1.0F);
}

public - the scope of the function. It determines how it can be accessed.

void - the return type. In C#, this has to be stated and it limits the type of information returned and how it can be used. "Void" means the function is not providing information to be used as a value (here, the game object is being made red).

MakeRed - the function name. This is the representative phrase or word and can be anything that is not already used, but there are some naming conventions and rules to follow to ensure it works.

parentheses ( ) - where arguments can be used to apply the function in specific ways.

curly brackets { } - hold the code to run when the function is called.

Calling a Function

The code within the brackets of a function only runs when it's called in other code that is running.

Example calling MakeRed() within another function, including Start() or Update():

// Make the current game object red
MakeRed();

Function Scope

Scope determines how a function can be used. They are private by default, but adding the scope when creating a function helps developers read code quickly.

Public functions allow other scripts to access the function. You can make a function public by typing "public" before the return type when creating a custom function for a script.

Private functions are only accessible by the script they are created in.

To call a function in another script you can use the GetComponent<>() function with the name of the script within the angled brackets <>.

Example:

// Accessing Example.cs also attached to this game object
gameObject.GetComponent<Example>().MakeRed();

Function Type

Generally, functions return a value. Functions can be created to determine a value or object and then the function name can be used as a variable with that information. The type needs to be placed before the function name. The "return" keyword is then used at the end of the function's code to provide the value.

Example:

public string SayYesOrNo()
    {
        string message;
        float randomNumber = Random.Range(0, 1.0F);

        if (randomNumber < 0.5)
        {
            message = "yes";
        }
        else
        {
            message = "no";
        }

        return message;
    }

Now, in another part of the code, this function can be called to have the string generated by SayYesOrNo():

print("The answer is " + SayYesOrNo());

This is one of the messages that prints to the console:

Please see the list of types in the variable section.

Function Naming Conventions and Rules

Generally, function names can be almost anything. However, there are some strict rules and some good practices.

Strict Rules

  1. User-defined names cannot match keywords used within the script (i.e. bool, public, for, return, etc.).

  2. Function names cannot match those within the same script with the same number of arguments.

  3. Cannot start with a number.

  4. No spaces.

  5. No special characters.

Conventions and Best Practices

  1. Use descriptive action names. Functions DO things and look similar to object constructors that create objects (such as Color), so having a verb in the name helps developers read the code.

  2. Use "Pascal casing" for function names. This is where the first letter in each word in the function name is capitalized. Examples: MakeRed, PickRandomObject, DetermineDirection, etc. The Unity editor will convert this into friendly component labels within the Inspector Tab.

Arguments

Arguments are values passed into the function to get different desired results based on those values.

Empty parentheses () after a function name means the function will perform the same functions each time.

To create a function that takes arguments, declare the temporary/local variable names within the parentheses, separated by commas. In C#, you must also put the type of variable you are declaring.

Example:

public string SayYesOrNo(float posLevel, string currentMsg)
{
    string message = currentMsg;
    float randomNumber = Random.Range(0, 1.0F);

    if (randomNumber < posLevel)
    {
        message += " yes";
    }
    else
    {
       message += " no";
    }

    return message;
}

This does the same thing as the SayYesOrNo() function with no arguments, but takes into account a value for posLevel and adds to an already defined string.

To call a function with arguments, put the values or variables within the parentheses:

string answerMessage = "The answer is";
float positivityLevel = 0.78F;

print(SayYesOrNo(positivityLevel, answerMessage));

The console will print something like:

Last updated