Struct Embedding in UnrealScript
Our first example demonstrates struct embedding in UnrealScript. While UnrealScript doesn’t have direct struct embedding like some other languages, we can achieve similar functionality using inheritance.
class Base extends Object;
var int num;
function string Describe()
{
return "base with num=" $ string(num);
}
class Container extends Base;
var string str;
function Container Init(int n, string s)
{
num = n;
str = s;
return self;
}
function string ToString()
{
return "Container={num: " $ string(num) $ ", str: " $ str $ "}";
}
function Example()
{
local Container co;
local Base b;
co = new class'Container'.Init(1, "some name");
// We can access the base's fields directly on co
`log("co=" $ co.ToString());
// We can also access the base's fields through the parent class
b = Base(co);
`log("also num:" @ b.num);
// Since Container extends Base, it inherits the Describe method
`log("describe:" @ co.Describe());
// In UnrealScript, all classes implicitly implement the Object interface
// So we don't need to explicitly declare an interface for this example
`log("describer:" @ Object(co).Describe());
}In this UnrealScript version:
We define a
Baseclass with anumfield and aDescribemethod.We create a
Containerclass that extendsBase, adding astrfield.We use inheritance to achieve a similar effect to struct embedding. The
Containerclass inherits all properties and methods fromBase.We create an
Initmethod forContainerto initialize its fields, as UnrealScript doesn’t support constructor overloading.We demonstrate accessing fields and methods from the base class.
In UnrealScript, all classes implicitly implement the
Objectinterface, so we don’t need to explicitly declare an interface for this example.We use the
logstatement (represented here by the`logmacro) instead offmt.Printforfmt.Printlnfor output.
To run this code in Unreal Engine:
- Create a new UnrealScript file with this code.
- Compile the script in your Unreal Engine project.
- You can then call the
Examplefunction from other parts of your game code or through the Unreal Engine console.
This example demonstrates how UnrealScript uses inheritance to achieve functionality similar to struct embedding, allowing for a form of composition and method inheritance.