If Else in UnrealScript

Branching with if and else in UnrealScript is straightforward.

class IfElseExample extends Object;

function Execute()
{
    // Here's a basic example.
    if (7 % 2 == 0)
    {
        `log("7 is even");
    }
    else
    {
        `log("7 is odd");
    }

    // You can have an `if` statement without an else.
    if (8 % 4 == 0)
    {
        `log("8 is divisible by 4");
    }

    // Logical operators like `&&` and `||` are often useful in conditions.
    if (8 % 2 == 0 || 7 % 2 == 0)
    {
        `log("either 8 or 7 are even");
    }

    // A statement can precede conditionals; any variables
    // declared in this statement are available in the current
    // and all subsequent branches.
    local int num;
    num = 9;
    if (num < 0)
    {
        `log(num @ "is negative");
    }
    else if (num < 10)
    {
        `log(num @ "has 1 digit");
    }
    else
    {
        `log(num @ "has multiple digits");
    }
}

defaultproperties
{
}

To run this code, you would typically include it in a larger UnrealScript project and call the Execute function from elsewhere in your game code.

Note that in UnrealScript:

  1. We use the backtick (`) for logging instead of a print function.
  2. The @ operator is used for string concatenation.
  3. Variables need to be declared before they’re used, typically at the beginning of a function or in the class scope.
  4. There’s no direct equivalent to Go’s := operator for simultaneous declaration and assignment.

UnrealScript uses parentheses around conditions, unlike Go, but the braces are still required for the body of the if statement.

UnrealScript doesn’t have a ternary operator either, so you’ll need to use a full if statement even for basic conditions.

This example demonstrates basic conditional logic in UnrealScript, which is a crucial part of game programming for controlling game flow, character behavior, and more.