Tuesday, October 11, 2011

Using Functions in UnrealScript

The functions in UnrealScript are code blocks defined within the classes. In other object-oriented programming languages these functions are known as methods. A function in UnrealScript is declare as follows:

function returnType functionName(paramType1 param1, paramType2 param2 ... )

The return type and parameters are optional. To return a value of the function, use the command "return".

Functions can be overridden in subclasses. For example, the class Actor has a function called PostBeginPlay() that is called when an actor enter into the game. If we create a subclass of Actor we can write a new version of the function PostBeginPlay() in our subclass. In such cases it is recommended that the new function call the original version of the parent class. To do that use the word Super:

Super.PostBeginPlay();

UnrealScript does not support function overloading. Therefore, it is not possible to create functions in the same class with the same name and different parameters.

There are several functions that are defined with the keyword event in the Actor class. The only difference is that functions defined with the event keyword can be called from C++ code.

Functions can have output parameters. This is useful when a function needs to return more than one value. To use output parameters, use the keyword out before the parameter.

We can assign default values for parameters using the optional keyword.

There are a lot of general purpose functions already defined in UnrealScript such as functions for Log and Mathematical functions.

Code sample:
class TestFunctions extends Actor;

event PostBeginPlay()
{
   local float damage;
   local int num1, num2;

   Super.PostBeginPlay();
 
   damage = calculateDamage(125, 15);
   `log( "Damage Received: " $ damage);

   createTwoRandom(num1, num2);
   `log( "1st Number created : " $ num1);
   `log( "2nd Number created : " $ num2);
}

function float calculateDamage(float powerAttack, int defenseLevel)
{
   return (powerAttack * 10) / defenseLevel;
}

function createTwoRandom(out int number1, out int number2, optional int maxValue = 10)
{
   number1 = Rand(maxValue);
   number2 = Rand(maxValue);
}