Functions in UnrealScript

Our first example demonstrates functions in UnrealScript. We’ll explore functions with a few different examples.

class ExampleFunctions extends Object;

// Here's a function that takes two integers and returns their sum as an integer.
function int Plus(int A, int B)
{
    // UnrealScript automatically returns the value of the last expression,
    // but we'll use an explicit return for clarity.
    return A + B;
}

// When you have multiple consecutive parameters of the same type,
// you need to specify the type for each parameter in UnrealScript.
function int PlusPlus(int A, int B, int C)
{
    return A + B + C;
}

// The 'static' function in UnrealScript is similar to 'main' in some other languages.
static function ExecuteExample()
{
    local int Result;

    // Call a function as you'd expect, with name(args).
    Result = Default.Plus(1, 2);
    `log("1+2 =" @ Result);

    Result = Default.PlusPlus(1, 2, 3);
    `log("1+2+3 =" @ Result);
}

To run this code in UnrealScript, you would typically include it in a larger project and call the ExecuteExample function. The output would be logged to the Unreal Engine log:

1+2 = 3
1+2+3 = 6

UnrealScript has some differences from other languages:

  1. Functions are defined within a class.
  2. The static keyword is used for functions that don’t require an instance of the class.
  3. Local variables are declared with the local keyword.
  4. String concatenation uses the @ operator.
  5. Logging is done with the `log command.

UnrealScript doesn’t have a direct equivalent to multiple return values, but you can achieve similar functionality using out parameters or struct returns.

[Next Example: Multiple Return Values (or equivalent concept in UnrealScript)]