Interfaces in UnrealScript

// Here's a basic interface for geometric shapes.
interface Geometry
{
    function float Area();
    function float Perim();
}

// For our example we'll implement this interface on
// Rectangle and Circle classes.
class Rectangle extends Object implements Geometry
{
    var float Width, Height;

    // To implement an interface in UnrealScript, we need to
    // implement all the methods in the interface.
    function float Area()
    {
        return Width * Height;
    }

    function float Perim()
    {
        return 2 * Width + 2 * Height;
    }
}

class Circle extends Object implements Geometry
{
    var float Radius;

    // The implementation for Circle.
    function float Area()
    {
        return Pi * Radius * Radius;
    }

    function float Perim()
    {
        return 2 * Pi * Radius;
    }
}

// If a variable has an interface type, then we can call
// methods that are in the named interface. Here's a
// generic Measure function taking advantage of this
// to work on any Geometry.
function Measure(Geometry G)
{
    `log(string(G));
    `log(string(G.Area()));
    `log(string(G.Perim()));
}

// Main function to demonstrate usage
function Demo()
{
    local Rectangle R;
    local Circle C;

    R = new class'Rectangle';
    R.Width = 3;
    R.Height = 4;

    C = new class'Circle';
    C.Radius = 5;

    // The Circle and Rectangle classes both
    // implement the Geometry interface so we can use
    // instances of these classes as arguments to Measure.
    Measure(R);
    Measure(C);
}

In UnrealScript, interfaces are used similarly to other object-oriented languages. They define a contract that classes must fulfill by implementing specific methods. Here’s how the concepts translate:

  1. We define an interface Geometry with two methods: Area() and Perim().

  2. We create two classes, Rectangle and Circle, both implementing the Geometry interface.

  3. Each class provides its own implementation of the Area() and Perim() methods.

  4. We create a Measure() function that takes a Geometry parameter, allowing it to work with any object that implements the Geometry interface.

  5. In the Demo() function, we create instances of Rectangle and Circle, and demonstrate how they can both be passed to the Measure() function.

Note that UnrealScript uses extends Object to define a new class, and implements to specify which interfaces a class implements. Also, UnrealScript uses backticks for its logging function, so we use `log instead of fmt.Println.

To run this code in an Unreal Engine environment, you would typically place it in an appropriate script file and either call the Demo() function from elsewhere in your game logic, or set it up to run when needed within the Unreal Engine framework.