UDN
Search public documentation:
UnrealScriptFunctions
日本語訳
中国翻译
한국어
Interested in the Unreal Engine?
Visit the Unreal Technology site.
Looking for jobs and company info?
Check out the Epic games site.
Questions about support via UDN?
Contact the UDN Staff
中国翻译
한국어
Interested in the Unreal Engine?
Visit the Unreal Technology site.
Looking for jobs and company info?
Check out the Epic games site.
Questions about support via UDN?
Contact the UDN Staff
UnrealScript Functions
Overview
Declaring Functions
// Function to get the team a player is on
function byte GetTeam(Pawn PlayerPawn)
{
return PlayerPawn.Controller.Team;
}
Function Signature
The first line of the function declaration defines how the function is identified and addressed. This is called the function's signature. The signature specifies the name of the function, what values it can take in through function parameters, what (if any) return value it outputs, and any other pertinent information about the function through the use of function specifiers. The most basic function signature begins with thefunction
keyword (special event functions begin event
keyword instead). This is followed by the optional return type of the function, then the function name, and then the list of function parameters enclosed in parenthesis.
From the example declaration above, the signature portion is:
function byte GetTeam(Pawn PlayerPawn)
GetTeam
that takes in a reference to a Pawn
and returns an byte
value (which you can guess by the name of the function represents the team of the Pawn
that was passed in).
Functions can also have certain attributes determined by the use of function specifiers in the declaration. These generally precede the function
(or event
) keyword in the signature, though some must be placed in other locations.
Function Body
Following the signature is a set of curly braces that contain all of the commands that belong to the function. This is known as the function's body. When a function is called, the code within the body is executed in sequential order from top to bottom. Inside the function's body, you can declare local variables (using thelocal
keyword) and execute any valid UnrealScript code. Execution of the function body ends when either a return statement or the closing curly brace is reached.
From the example declaration above, the body portion is:
{ return PlayerPawn.Controller.Team; }
FALSE
for Bool
, None
for Object references, etc).
Return Type and Value
function int GetHealth(Pawn PlayerPawn)
int
value. Any UnrealScript type can be used as a return type.
In order to return a value from the function, the return
keyword is used followed by the value to return. This is called a return statement and it causes the function to immediately cease execution and return the value specified. If the function declares a return type, it must return a value using a return statement.
function int GetHealth(Pawn PlayerPawn) { return PlayerPawn.Health; }
Health
variable of the Pawn
that was passed to the function.
A function can also have multiple return statements, though only one will ever be used each time the function is executed. If the function body contains multiple paths the code can take (for instance when using control statements), each path must contain a return statement or a catch-all return statement must be located at the end of the function body.
function bool IsAlive(Pawn PlayerPawn) { if(PlayerPawn.Health > 0) { return true; } else { return false; } }
Bool
values the function can return, but obviously only one of them will be executed each time depending on whether the Pawn
is alive or not.
Function Parameters
function int GetHealth(Pawn PlayerPawn)
PlayerPawn
that is a reference to a Pawn
. A function parameter can be any UnrealScript type.
Parameters are accessed within the body of the function the same way any other variable is accessed; by using the name of the parameter.
Function Parameter Specifiers
- Out
- When you normally call a function, UnrealScript makes a local copy of the parameters you pass the function. If the function modifies some of the parameters, those don't have any effect on the variables you passed in. For example, the following program:
function int DoSomething( int x ) { x = x * 2; return x; } function int DoSomethingElse() { local int a, b; a = 2; log( "The value of a is " $ a ); b = DoSomething( a ); log( "The value of a is " $ a ); log( "The value of b is " $ b ); }
DoSomethingElse
is called:The value of a is 2 The value of a is 2 The value of b is 4
DoSomething
was futzing with a local copy of the variablea
which was passed to it, and it was not affecting the real variablea
.
Theout
specifier lets you tell a function that it should actually modify the variable that is passed to it, rather than making a local copy. This is useful, for example, if you have a function that needs to return several values to the caller. You can juse have the caller pass several variables to the function which areout
values. For example:// Compute the minimum and maximum components of a vector. function VectorRange( vector V, out float Min, out float Max ) { // Compute the minimum value if ( V.X<V.Y && V.X<V.Z ) Min = V.X; else if( V.Y<V.Z ) Min = V.Y; else Min = V.Z; // Compute the maximum value. if ( V.X>V.Y && V.X>V.Z ) Max = V.X; else if( V.Y>V.Z ) Max = V.Y; else Max = V.Z; }
out
keyword, it would be painful to try to write functions that had to return more than one value. Out parameters are passed by reference so modifying the parameter's value in the function will immediately affect the original. This can also be used as an optimization for large values, similiarly to C++, by specifying "const out". - Optional
- With the
optional
keyword, you can make certain function parameters optional, as a convenience to the caller. For UnrealScript functions, optional parameters which the caller doesn't specify are set to the default value given in the function declaration, or zero (e.g. 0, false, "", none) if no value was specified in the function signature. For native functions, the default values of optional parameters depends on the function. For example, the Spawn function takes an optional location and rotation, which default to the spawning actor's location and rotation. The default value of optional arguments can be specified by adding= value
. For examplefunction myFunc(optional int x = -1)
. - Coerce
- The
coerce
keyword forces the caller's parameters to be converted to the specified type (even if UnrealScript normally would not perform the conversion automatically). This is useful for functions that deal with strings, so that the parameters are automatically converted to strings for you. (See Unreal Strings)
Function Specifiers
- Static
- A static function acts like a C global function, in that it can be called without having a reference to an object of the class. Static functions can call other static functions, and can access the default values of variables. Static functions cannot call non-static functions and they cannot access instance variables (since they are not executed with respect to an instance of an object). Unlike languages like C++, static functions are virtual and can be overridden in child classes. This is useful in cases where you wish to call a static function in a variable class (a class not known at compile time, but referred to by a variable or an expression).
- Singular
- The
singular
keyword, which appears immediately before a function declaration, prevents a function from calling itself recursively. The rule is this: If a certain actor is already in the middle of a singular function, any subsequent calls to singular functions will be skipped over. This is useful in avoiding infinite-recursive bugs in some cases. For example, if you try to move an actor inside of your Bump function, there is a good chance that the actor will bump into another actor during its move, resulting in another call to the Bump function, and so on. You should be very careful in avoiding such behavior, but if you can't write code with complete confidence that you're avoiding such potential recursive situations, use thesingular
keyword. Note that this is not limited just to the particular function that is flagged singular -- all singular functions within a single object will not execute if you are currently in a singular function that is executing. - Native
- You can declare UnrealScript functions as
native
, which means that the function is callable from UnrealScript, but is actually implemented (elsewhere) in C++. For example, the Actor class contains a lot of native function definitions, such as:native(266) final function bool Move( vector Delta );
native
keyword corresponds to the number of the function as it was declared in C++ (using theAUTOREGISTER_NATIVE
macro), and is only required for operator functions. The native function is expected to reside in the DLL named identically to the package of the class containing the UnrealScript definition. - NoExport
- Only used for native functions. Declares that the C++ function declaration for this native function should not be exported. Only the declaration for the glue version of the function will be exported.
- Exec
- Indicates that this function can be executed by typing the name of the function into the console. Only valid in certain classes.
- Latent
- Declares that a native function is latent, meaning that it can only be called from state code, and it may return after some game-time has passed.
- Iterator
- Declares that a native function is an iterator, which can be used to loop through a list of actors using the
foreach
command. - Simulated
- Declares that a function may execute on the client-side when an actor is either a simulated proxy or an autonomous proxy. All native functions are automatically simulated as well. (Note: if you override a virtual native with a non-native function, the non-native override will NOT be simulated unless this keyword is specified)
- Server
- Declares that a function should be sent to the server for execution instead of running on the local client.
- Client
- Declares that a function should be sent to the owning client for execution instead of running on the server. This flag also implicitly sets the
simulated
flag for the function. - Reliable
- Declares that a replicated function (marked with either
server
orclient
) should be reliably sent, meaning it will always eventually reach the other end in order relative to other replication on that Actor. - Unreliable
- Declares that a replicated function (marked with either
server
orclient
) should be unreliably sent, meaning that it is not guaranteed to reach the other end in any particular order or at all and may be skipped completely if there is insufficient bandwidth available. - Private, Protected
- These keywords have the same meaning as the corresponding variable keywords.
- Operator, PreOperator, PostOperator
- These keywords are for declaring a special kind of function called an operator (equivalent to C++ operators). This is how UnrealScript knows about all of the built-in operators like "+", "-", "==", and "||". I'm not going into detail on how operators work in this document, but the concept of operators is similar to C++, and you can declare new operator functions and keywords as UnrealScript functions or native functions.
- Event
- Used in place of the
function
keyword when declaring a function that can be executed from native C++ engine code. See Events for more information. - Const
- Can only be used with native declared function and this specifier is added after the function declaration. This specifier will determine whether this function should be exported as 'const' in the generated header. Example usage:
native function int doSomething(string myData) const;
Function Overriding
Demon
. The Demon
class, which you just created, extends the Pawn
class. Now, when a pawn sees a player for the first time, the pawn's SeePlayer
function is called, so that the pawn can start attacking the player. This is a nice concept, but say you wanted to handle SeePlayer
differently in your new Demon
class. How do you do this? Function overriding is the answer.
To override a function, just cut and paste the function definition from the parent class into your new class and modify the body. The signature for the function in your class should match the signature in the parent class as far as name, specifiers, return type, and parameters (the names of the parameters can change, but the number and type must remain the same). For example, for SeePlayer
, you could add this to your Demon
class.
// New Demon class version of the Touch function. function SeePlayer( actor SeenPlayer ) { log( "The demon saw a player" ); // Add new custom functionality here... }
final
. The final
keyword (which appears immediately before the word function
) says "this function cannot be overridden by child classes". This should be used in functions that you know nobody would want to override, because it results in faster script code. For example, say you have a VectorSize
function that computes the size of a vector. There's absolutely no reason anyone would ever override that, so declare it as final
. On the other hand, a function like Touch
is very context-dependent and should not be final.
Executing Functions
function SetCollision( optional bool bNewColActors, optional bool bNewBlockActors, optional bool bNewIgnoreEncroachers );
SetCollision(true, true, true);
Trace()
function has several optional parameters:
/**
* Trace a line and see what it collides with first.
* Takes this actor's collision properties into account.
* Returns first hit actor, Level if hit level, or None if hit nothing.
*/
function Actor Trace
(
out vector HitLocation,
out vector HitNormal,
vector TraceEnd,
optional vector TraceStart,
optional bool bTraceActors,
optional vector Extent,
optional out TraceHitInfo HitInfo,
optional int ExtraTraceFlags
);
TraceStart
and bTraceActors
parameters, but including the Extent
parameter, the call would look something like this (assuming HitLocation
, HitNormal
, and End
are all local Vector
variables declared previously):
Trace(HitLocation, HitNormal, End,,,vect(4,4,4));
Function Calling Specifiers
- Global
- Calls the most-derived global (non-state) version of the function.
- Super
- Calls the corresponding version of the function in the parent class. The function called may either be a state or non-state function depending on context.
- Super(classname)
- Calls the corresponding version of the function residing in (or above) the specified class. The function called may either be a state or non-state function depending on context.
Super(Actor).Global.Touch
).
Here are some examples of calling specifiers:
class MyClass extends Pawn; function MyExample( actor Other ) { Super(Pawn).Touch( Other ); Global.Touch( Other ); Super.Touch( Other ); }
BeginPlay()
function is called when an actor is about to enter into gameplay. The BeginPlay()
function is implemented in the Actor
class and it contains some important functionality that needs to be executed. Now, say you want to override BeginPlay()
in your new class MyClass
, to add some new functionality. To do that safely, you need to call the version of BeginPlay()
in the parent class:
class MyClass extends Pawn; function BeginPlay() { // Call the version of BeginPlay in the parent class (important). Super.BeginPlay(); // Now do custom BeginPlay stuff. //... }
Events
event
keyword instead of the usual function
keyword.
For example, when an actor is touched by another actor, the engine calls its Touch
event to tell it who is touching it.
event Touch( Actor Other, PrimitiveComponent OtherComp, vector HitLocation, vector HitNormal );
Touch
function, you can take special actions as a result of the touch occurring:
// Called when something touches this actor.
function Touch( actor Other )
{
`log( "I was touched!")
Other.Message( "You touched me!" );
}
`log
command (which is the equivalent of Basic's print
command and C's printf
, with the exception on formatting rules). Second, it calls the "Message" function residing in the actor Other. Calling functions in other actors is a common action in UnrealScript, and in object-oriented languages like Java in general, because it provides a simple means for actors to communicate with each other.
Function Recursion
// Function to compute the factorial of a number.
function int Factorial( int Number )
{
if( Number <= 0 )
return 1;
else
return Number * Factorial( Number - 1 );
}
Static Functions
var class C; var classPC; class'SkaarjTrooper'.static.SomeFunction(); // Call a static function // in a specific class. PC.static.SomeFunction(); // Call a static function in a variable class. class (C).static.SomeFunction(); // Call a static function in a //casted class expression.
Timers
Timer()
function called either once, or recurring, after a set amount of time has passed.
UnrealScript timers are just implemented as an array of structs inside each Actor (an Actor can have multiple timers pending). The struct contains the amount of time remaining before the timer expires, the function to call on expiry, etc.
The game loop normally ticks each Actor once per frame, and part of each Actor's Tick()
function includes a call to UpdateTimers()
which will check for any expired timers and call their appropriate UnrealScript function.
The granularity is limited to the frame delta time, but there are no hardware or OS resources required. All of this is implemented in C++ so you could safely update hundreds of UnrealScript timers without any cause for concern. Of course you wouldn't want them all expiring simultaneously or every frame because they execute (slow) script code when they're activated.
Timer functions are only available to Actor
subclasses.
You can create multiple timers with each a different rate. Each timer has a unique target function (defaults to Timer()
).
- function SetTimer(float inRate, optional bool inbLoop, optional Name inTimerFunc)
- Start a timer that is triggered after
inRate
seconds. IfinbLoop
is true the timer will loop.inTimerFunc
defines the function to call, by default this is the functionTimer()
, this value is also used to identify to multiple timers. - ClearTimer(optional Name inTimerFunc)
- stops a running timer.
- bool IsTimerActive(optional Name inTimerFunc)
- returns true if the given timer is active
- float GetTimerCount(optional Name inTimerFunc)
- returns the counter value of the timer, e.g. the number of seconds since the last time the timer was executed. Returns
-1
if the timer is not active. - float GetTimerRate(optional name TimerFuncName = 'Timer')
- returns the rate of timer,
GetTimerRate('SomeTimer') - GetTimerCount('SomeTimer')
will return the remaining time for the timer.
Built-In Functions
Object
, Actor
, etc.) that are extremely useful and very handy to know by heart when working in UnrealScript creating new classes for your game.
Creating objects
In order to create a new object instance in UnrealScript, you'll use one of two functions depending on whether the object is an Actor or not. For Actors, you must use the Spawn function, which is declared inActor.uc
. For non Actor-derived classes, you must use the new
operator. The syntax for the new operator is unlike that of any other function. In addition to an optional parameter list, you must specify the class of the new object and an optional template object. There is no UnrealScript declaration for the new operator, but here's what the function signature would look like:
native final operator function coerce Object new ( object InOuter, name InName, int InFlags, class InClass, object InTemplate );
- InOuter
- (optional) the object to assign as the
Outer
for the newly created object. If not specified, the object's Outer will be set to a special package which exists only while the game is running, called the "transient package". - InName
- (optional) the name to give the new object. If not specified, the object will be given a unique name in the format
ClassName_##
, where##
is incremented each time an instance of this class is created. - InFlags
- (optional, currently broken since object flags are now 64 bits) the object flags to use when creating the object. The valid values are:
-
0x0000000100000000
- Supports editor undo/redo. (RF_Transactional) -
0x0000000400000000
- Can be referenced by external files. (RF_Public) -
0x0000400000000000
- Cannot be saved to disk. (RF_Transient) -
0x0010000000000000
- Don't load object on the game client. (RF_NotForClient) -
0x0020000000000000
- Don't load object on the game server. (RF_NotForServer) -
0x0040000000000000
- Don't load object in the editor. (RF_NotForEdit) -
0x0008000000000000
- Keep object around for editing even if unreferenced. (RF_Standalone)
-
- InClass
- the class to create an instance of
- InTemplate
- the object to use for initializing the new object's property values
ObjectVar = new[(InOuter, InName, InFlags)] <class'InClass'>[(InTemplate)];
function CreateALight() { local LightFunction NewObj; NewObj = new class'Engine.LightFunction'; }
function CreateALight() { local LightFunction NewObj; NewObj = new(Self,'NewLight') class'Engine.LightFunction'; }
var LightFunction LightFunctionTemplate; function CreateALight() { local LightFunction NewObj; NewObj = new(None,'NewLight') class'Engine.LightFunction' (LightFunctionTemplate); } defaultproperties { Begin Object Class=LightFunction Name=MyLightFunctionArchetype End Object LightFunctionTemplate=MyLightFunctionArchetype }
Integer functions
- int Rand( int Max )
- Returns a random number from 0 to Max-1.
- int Min( int A, int B )
- Returns the minimum of the two numbers.
- int Max( int A, int B )
- Returns the maximum of the two numbers.
- int Clamp( int V, int A, int B )
- Returns the first number clamped to the interval from A to B.
Floating point functions
- float Abs( float A )
- Returns the absolute value of the number.
- float Sin( float A )
- Returns the sine of the number expressed in radians.
- float Cos( float A )
- Returns the cosine of the number expressed in radians.
- float Tan( float A )
- Returns the tangent of the number expressed in radians.
- float ASin( float A )
- Returns the inverse sine of the number expressed in radians.
- float ACos( float A )
- Returns the inverse cosine of the number expressed in radians.
- float Atan( float A )
- Returns the inverse tangent of the number expressed in radians.
- float Exp( float A )
- Returns the constant "e" raised to the power of A.
- float Loge( float A )
- Returns the log (to the base "e") of A.
- float Sqrt( float A )
- Returns the square root of A.
- float Square( float A )
- Returns the square of A = A*A.
- float FRand()
- Returns a random number from 0.0 to 1.0.
- float FMin( float A, float B )
- Returns the minimum of two numbers.
- float FMax( float A, float B )
- Returns the maximum of two numbers.
- float FClamp( float V, float A, float B )
- Returns the first number clamped to the interval from A to B.
- float Lerp( float A, float B, float Alpha )
- Returns the linear interpolation between A and B.
- float Smerp( float Alpha, float A, float B )
- Returns an Alpha-smooth nonlinear interpolation between A and B.
- float Ceil( float A )
- Rounds up
- float Round( float A )
- Rounds normally
String functions
- int Len( coerce string S )
- Returns the length of a string.
- int InStr( coerce string S, coerce string t)
- Returns the offset into the first string of the second string if it exists, or -1 if not.
- string Mid( coerce string S, int i, optional int j )
- Returns the middle part of the string S, starting and character i and including j characters (or all of them if j is not specified).
- string Left( coerce string S, int i )
- Returns the i leftmost characters of S.
- string Right( coerce string] S, int i )
- Returns the i rightmost characters of S.
- string Caps( coerce string S )
- Returns S converted to uppercase.
- string Locs( coerce string S)
- Returns the lowercase representation of S (v3323 and up)
- string Chr( int i )
- Returns a character from the ASCII table
- int Asc( string S )
- Returns the ASCII value of a character (only the first character from the string is used)
- string Repl( coerce string Src, coerce string Match, coerce string With, optional bool bCaseSensitive )
- Replace
Match
withWith
in the source. (v3323 and up) - string Split(coerce string Text, coerce string SplitStr, optional bool bOmitSplitStr)
- Splits
Text
on the first occurrence ofSplitStr
and returns the remaining part ofText
. IfbOmitSplitStr
is true,SplitStr
will be omitted from the returned string. - array<string> SplitString( string Source, optional string Delimiter=",", optional bool bCullEmpty )
- Wrapper for splitting a string into an array of strings using a single expression.
- JoinArray(array<string> StringArray, out string out_Result, optional string delim = ",", optional bool bIgnoreBlanks = true)
- Create a single string from an array of strings, using the delimiter specified, optionally ignoring blank members.
- ParseStringIntoArray(string BaseString, out array<string> Pieces, string Delim, bool bCullEmpty)
- Breaks up a delimited string into elements of a string array.
- A == B
- Comparison that returns true if both strings are the same (Case Sensitive).
- A ~= B
- Comparison that returns true if both strings are the same (NOT Case Sensitive).
- A != B
- Comparison that returns true if the strings are different (Case Sensitive).
Vector functions
- vector vect( float X, float Y, float Z )
- Creates a new vector with the given components.
- float VSize( vector A )
- Returns the euclidean size of the vector (the square root of the sum of the components squared).
- vector Normal( vector A )
- Returns a vector of size 1.0, facing in the direction of the specified vector.
- Invert( out vector X, out vector Y, out vector Z )
- Inverts a coordinate system specified by three axis vectors.
- vector VRand()
- Returns a uniformly distributed random vector.
- vector MirrorVectorByNormal( vector Vect, vector Normal )
- Mirrors a vector about a specified normal vector.
Debugging functions
The following functions can aid you in debugging your code.- LogEx( ELoggingSeverity Severity, name Category, coerce string Msg )
- Log a message with a given severity and category. This function gives more control that the standard log() function. It allows you to filter log messages based on severity and category in runtime.
- LogFatal( name Category, coerce string Msg )
- shorthand for calling
LogEx(LOG_FATAL, Category, Msg)
- LogError( name Category, coerce string Msg )
- TODO
- function LogWarn( name Category, coerce string Msg )
- TODO
- LogInfo( name Category, coerce string Msg )
- TODO
- LogDebug( name Category, coerce string Msg )
- TODO
- LogTrace( name Category, coerce string Msg )
- TODO
- ScriptTrace()
- Dumps the current script call stack to the log file
- Name GetFuncName()
- Returns the current calling function's name
- DumpStateStack()
- Logs the current state stack