Unity Out Keyword

In by John FrenchPublished

The out keyword in Unity is used to return extra information from a function in addition to its return type.

When creating a function parameter it reverses the flow of data, so that instead of taking data in, a function’s argument can be used to pass data out instead.

Normally, when calling a function, you pass data into it via its parameters and get information back via its return type.

It’s likely that you’ll have already written functions with a void return type, meaning they don’t return any information.

Other functions, on the other hand, may specify what type of data is returned from the function when it runs.

For example a bool:

bool IsAboveTen(float num)
{ 
    if(num > 10)
    {
        return true;
    }
    else {
        return false;
    }
}

In this example, Is Above Ten returns a true or false condition depending on the number that’s passed into it.

Meaning you can set a boolean variable just by calling the function.

Like this:

void Start()
{
    bool result = IsAboveTen(20);
    // result will be set to true;
}

A function can only have one return type, but the out keyword allows you to return extra information from a function.

For example… I could make the function return a bool, but also store a string based on the result.

Like this:

public string numResult;

private void Start()
{
    bool result = IsAboveTen(20, out numResult);
    Debug.Log(numResult);
}

bool IsAboveTen(float num, out string result)
{
    if (num > 10)
    {
        result = "The number was more than 10!";
        return true;
    }
    else
    {
        result = "The number was not more than 10!";
        return false;
    }
}

The out keyword means that, instead of passing information into the method via that parameter, extra data will be returned back from it and will need a place to be stored.

With the Raycast function, for example, where you’ll commonly see the out keyword used to store the Raycast Hit data, if there is any.

void FireRay()
{
    Ray ray = new Ray(transform.position, transform.forward);
    RaycastHit hitData;

    Physics.Raycast(ray, out hitData);
}