Structs in UnrealScript

Structs

UnrealScript’s structs are typed collections of fields. They’re useful for grouping data together to form records.

This Person struct type has name and age fields.

struct Person {
    var string name;
    var int age;
};

newPerson constructs a new Person struct with the given name.

function Person newPerson(string name) {
    local Person p;
    p.name = name;
    p.age = 42; // default age
    return p;
}

UnrealScript manages memory using a combination of garbage collection and manual memory management. Local variables and function parameters are automatically cleaned up, so you don’t need to worry about explicitly freeing them.

function main() {
    local Person p;
    
    // This syntax creates a new struct
    p.name = "Bob";
    p.age = 20;
    `Log(p);  // equivalent to fmt.Println in Go

    // You can name the fields when initializing a struct
    p = new Person(name="Alice", age=30);
    `Log(p);

    // Omitted fields will be zero-valued
    p = new Person(name="Fred");
    `Log(p);

    // It’s idiomatic to encapsulate new struct creation in constructor functions
    p = newPerson("Jon");
    `Log(p);

    // Access struct fields with a dot
    `Log(p.name);

    // You can also use references to structs
    local Person sp;
    sp = p;
    `Log(sp.age);

    // Structs are mutable
    sp.age = 51;
    `Log(sp.age);

    // Example of anonymous structs
    local struct {
        var string name;
        var bool isGood;
    } Dog;
    
    Dog.name = "Rex";
    Dog.isGood = true;
    `Log(Dog);
}

To run the program, ensure your UnrealScript environment is correctly set up. Then compile the script and execute it in the Unreal Engine context.

# Compile the script
ucc make

# The output should contain expected log messages
# Equivalent to running the Go program

Now that we can run and build basic UnrealScript programs, let’s learn more about the language.