Variables: Difference between revisions

From Unreal Wiki, The Unreal Engine Documentation Site
Ikuto (talk | contribs)
New page: == Important notice to editors == {{stub}} This article is a stub to relation of the fact, that primarily article creator have mainly filled in stuff about Unreal Engine 1 a...
 
m Modifiers: somehow the struct member tag got lost when moving modifier info to a template
 
(31 intermediate revisions by 8 users not shown)
Line 1: Line 1:
== Important notice to editors ==
[[wp:Variable#Computer programming|Variables]] are named storage slots for pieces of data. All [[UnrealScript]] variables are [[wp:static typing|staticly-typed]], that means you can only store a specific type of data in them and the type of data is defined in the variable [[wp:declaration (computer science)|declaration]].
{{stub}}
This article is a stub to relation of the fact, that primarily [[User:Ikuto|article creator]] have mainly filled in stuff about Unreal Engine 1 and some aspects of Unreal Engine 2. Any help on expanding this article with Unreal Engine 2 and Unreal Engine 3 stuff will be much appreciated.


__TOC__
There are three basic types of variables in UnrealScript:
* Class variables, which can only be declared at the [[class]] [[wp:Scope (programming)|scope]], before any function, operator, delegate or [[state]] declaration.
* Struct members, which are declared inside their [[struct]]'s declaration block.
* Local variables, which can be declared at the start of [[function]], [[state]], [[operator]] and [[delegate]] bodies before any code statements. (For readability's sake, this article will imply operators and delegates when it mentions functions, unless otherwise noted.)


== Simple Variables ==
==Declaration==
A simple class or struct member variable declaration looks like this:
'''var''' ''[[#Modifiers|[modifiers]]]'' [[type]] variablename''''';'''
The ''variablename'' can be any combination of the letters A-Z (case-insensitive), the digits 0-9 and the underscore character _ with two restrictions:
* The name may not start with a digit.
* The name must be shorter than 64 characters.
The ''type'' can not only be a type specification, but also a [[struct]] or [[enum]] declaration.


Here are some examples of instance variable declarations in UnrealScript:
You can declare multiple variables of the same type in one declaration:
'''var''' ''[[#Modifiers|[modifiers]]]'' [[type]] variablename1''',''' variablename2''',''' ...''';'''
Each of the variable names may optionally have an array size specification to create a [[static array]]:
variablename'''['''arraysize''']'''
You can mix static arrays and non-array variables in a single declaration. The array size only applies to the variable you appended it to.


<uscript>var int a; // Declare an integer variable named "A".
===Editable variables===
var byte Table[64]; // Declare an array of 64 bytes named "Table".
To make the variable accessible from within [[UnrealEd]]'s property windows, use the following syntax:
var string[32] PlayerName; // Declare a max 32-character string.
'''var('''''[groupname[,subgroup<sup>3</sup>]]''''')''' ''[[#Modifiers|[modifiers]]]'' [[type]] variablename''';'''
var actor Other; // Declare a variable referencing an actor.</uscript>
The ''groupname'' must be an identifier if specified. If omitted, the class name is used as group name. For struct members, the group name has no effect.


Variables can appear in two kinds of places in UnrealScript: instance variables, which apply to an entire object, appear immediately after the class declarations. Local variables appear within a function, and are only active while that function executes. Instance variables are declared with the "var" keyword. Local variables are declard with the "local" keyword.
===Local variables===
Local variable declarations in [[function]] bodies are similar, but a bit simpler:
'''local''' [[type]] variablename''';'''
Local variables must be declared at the very top of the function body, between the <code>{</code> and the first line of "executable" code.


Here are the basic variable types supported in UnrealScript:
You can declare static arrays and multiple variables of the same type as described for class and struct variables above. The ''type'' must be an existing type. It is not allowed to declare new structs or enums here.


* byte: A single-byte value ranging from 0 to 255.  
After declaration, a local variable is initially null, which can mean different things, depending on the variable type. (Zero for numeric types, False, empty string or array, None, etc.)
* int: A 32-bit integer value.
* bool: A boolean value: either "true" or "false".
* float: A 32-bit floating point number.
* string: A string of characters.
* name: The name of an item in Unreal (such as the name of a function, state, class, etc). Names are stored as a 16-bit index into the global name table. Names correspond to simple strings of 1-31 characters. Names are not like strings: strings can be modified dynamically, but names can only take on predefined name values.


* Enumeration: A variable that can take on one of several predefined name values. For example, the ELightType enumeration defined in the Actor script describes a dynamic light and takes on a value like LT_None, LT_Pulse, LT_Strobe, and so on.
* Object and actor references: A variable that refers to another object or actor in the world. For example, the Pawn class has an "Enemy" actor reference that specifies which actor the pawn should be trying to attack. Object and actor references are very powerful tools, because they enable you to access the variables and functions of another actor. For example, in the Pawn script, you can write "Enemy.Damage(123)" to call your enemy's Damage function – resulting in the enemy taking damage. Object references may also contain a special value called "None", which is the equivalent of the C "NULL" pointer: it says "this variable doesn't refer to any object".


* Structs: Similar to C structures, UnrealScript structs let you create new variable types that contain sub-variables. For example, two commonly-used structs are "vector", which consists of an X, Y, and Z component; and "rotator", which consists of a pitch, yaw, and roll component.
'''Note''': As of UDK 2011-06+?{{confirm}} it is also possible to declare local variables in [[state]]s. Local variables must be declared before [[ignores]].


Variables may also contain additional specifiers such as "const" that further describe the variable. Actually, there are quite a lot of specifiers which you wouldn't expect to see in a general-purpose programming language, mainly as a result of wanting UnrealScript to natively support many game- and environment- specific concepts:
==Modifiers==
For class and struct variables you are allowed to specify one or more variable modifiers. These change the way the variable works in certain situations.
{{Infobox EngineVersion|modifier}}
Modifiers tagged with '''<sup>S</sup>''' can be used for struct members.


* const: Advanced. Treats the contents of the variable as a constant. In UnrealScript, you can read the value of const variables, but you can't write to them. "Const" is only used for variables which the engine is responsible for updating, and which can't be safely updated from UnrealScript, such as an actor's Location (which can only be set by calling the MoveActor and SetLocation functions).
===Inner type modifiers===
* input: Advanced. Makes the variable accessible to Unreal's input system, so that input (such as button presses and joystick movements) can be directly mapped onto it. Only relevent with variables of type "byte" and "float".  
You can also specify variable modifiers for the inner type of a [[dynamic array]] declaration. This compiler feature is available in all engine versions, but doesn't have any effect before [[Unreal Engine 3]]. The only currently known instances of this are several variables in two classes of the [[UDK]]'s Engine package ([[UE3:NxForceField (UDK)|NxForceField]] and [[UE3:NxGenericForceFieldBrush (UDK)|NxGenericForceFieldBrush]], both using <code>[[array]]<const native transient [[pointer]]></code>), so this feature might only work at all in newer versions of Unreal Engine 3. '''Note''': All inner modifiers are as well implicity added to the variable modifiers, so for example if you were to add [[EditConst]] the actual variable would as well act upon [[EditConst]].
* transient: Advanced. Declares that the variable is for temporary use, and isn't part of the object's persistent state. Transient variables are not saved to disk. Transient variables are initialized to zero when an actor is loaded.
* native: Advanced. Declares that the variable is loaded and saved by C++ code, rather than by UnrealScript.
* private: The variable is private, and may only be accessed by the class's script; no other classes (including subclasses) may access it.
* editinline: Advanced. Indicates that object reference \ class reference can be expanded in actor \ object properties <Unreal Engine 2+>
* editconst: Advanced. Indicates that property can not be modified in the properties window


Arrays are declared using the following syntax:
===Access modifiers===
The following modifiers only apply to class variables and specify, which other classes are allowed to access the variable. The access rules are enforced by the compiler.
; Const<sup>S</sup>: Prevents any changes to this variable from within UnrealScript. You are still allowed to specify a value in the [[defaultproperties]] block and access the variable's value in your code. This property is mostly used to protect variables with a special meaning to native code. Classes with '''const''' variables usually have a corresponding setter function for each variable. With bytecode level hacking, it's possible to assign a value to a const variable, but in general, the effect is undefined (ranging from giving the result you want to crashing the game).
; Deprecated<sup>2,3</sup>: Signals that this variable should no longer be used. Accessing deprecated variables will throw a compiler warning. [[Unreal Engine 3]] will load the value of a '''deprecated''' variable, but ignore it during save.
; Private<sup>S,2,3</sup>: Private variables can only be accessed from within the class they were declared in. Other classes, even subclasses, can't access them.
; PrivateWrite<sup>3-x2</sup>: Related to the '''private''' access modifier. Causes the variable to be treated as private for writing, but public for reading.
; Protected<sup>S,2,3</sup>: Access to protected variables is only allowed from within the same class and its subclasses. Sibling classes, parent classes and other, unrelated classes can't "see" protected variables.
; ProtectedWrite<sup>3-x2</sup>: Related to the '''protected''' access modifier. Causes the variable to be treated as protected for writing, but public for reading.
; Public<sup>S,2,3</sup>: The default access rule. If no other access rule is specified, this is one is implied. Public variables can be accessed from any other class. Usually you will see this modifier in Unreal Engine 3, along with a native code snippet. One of the most common examples is <code>public{private}</code>, which means the variable is declared as public for UnrealScript, but as private for native code.


<uscript>var int MyArray[20]; // Declares an array of 20 ints.</uscript>
===Modifiers affecting values===
These modifiers affect the default value of the variable in some way.


UnrealScript supports only single-dimensional arrays, though you can simulate multidimensional arrays by carrying out the row/column math yourself.
; Automated<sup>UT2004</sup>: Only meaningful for object variables in [[UE2:GUIMultiComponent (UT2004)|GUIMultiComponent]] classes. Indicates that any [[UE2:GUIComponent (UT2004)|GUIComponent]] object(s) referenced by this variable should automatically be added to the [[UE2:GUIMultiComponent_(UT2004)#Controls|Controls]] array. Also works for [[static array|static]] and [[dynamic arrays]]. Objects that aren't GUIComponents are ignored.
::''Implies'': '''noexport''', '''editinline''', '''editinlineuse''' and '''editinlinenotify''', and FYI: any object variable(even parameters and locals) referencing GUIComponents implies '''export''' and '''editinline'''.
; Config<sup>S</sup>: Makes the variable configurable. The default variable value is read from an [[Legacy:INI_File|INI file]] when the class is loaded. Each subclass has its own version of the variable value in its INI file section. If the class is declared with the [[PerObjectConfig]] modifier, the initial instance value of the variable is read from a separate INI section for that object instance.
; DataBinding<sup>3</sup>: The variable can be manipulated by [[Unreal Engine 3]]'s data store system.
; DuplicateTransient<sup>3</sup>: Similar to '''transient''' (see below) but applies to object duplication.
; GlobalConfig<sup>S</sup>: Similar to the '''config''' modifier, but a '''globalconfig''' variable's default value is always read from the INI section of its declaring class, even for subclasses.
::''Implies'': '''config'''
; Input: Attaches the variable to the input system. This is only meaningful for float and byte variables, which can be tied to axis and button input respectively. Input variables are only filled for the local player actor.
; Instanced<sup>3</sup>: Only meaningful for reference variables. Subobjects assigned to instanced variables are duplicated when an instance of the class is created.
::''Implies'': '''export''' and '''editinline''' even on non-reference variables.
; Localized<sup>S</sup>: Makes the variable localizable. The default value of the variable is read from a [[localization file]] when the class is loaded. Each subclass can have its own localized versions of the variable value. In [[Unreal Engine 1]] and [[Unreal Engine 2|2]] and if the class is declared as [[PerObjectLocalized]] in [[Unreal Engine 3]], each instance of the class can have its own set of localized variable values. This is useful for actors placed in a map.
::''Implies'': '''const'''<sup>3</sup>
; Transient<sup>S</sup>: The variables is set to its null value when initializing object instances. The variable's value is never saved to disk in any way.
; Travel<sup>1,2</sup>: For single player gametypes where a player advances from one map to the next, carrying over all inventory items. Instance variables marked as '''travel''' will keep their value across the map change. Only has an effect for the PlayerPawn in UE1 (or the PlayerController and its Pawn in UE2) and its Inventory chain.


In UnrealScript, you can make an instance variable "editable", so that users can edit the variable's value in UnrealEd. This mechanism is responsible for the entire contents of the "Actor Properties" dialog in UnrealEd: everything you see there is simply an UnrealScript variable, which has been declared editable.
===Modifiers affecting UnrealEd===
These modifiers have some kind of effect in [[UnrealEd]], usually in the actor properties window.


The syntax for declaring an editable variable is as follows:
; EdFindable<sup>S,2</sup>: Adds a 'Find' button to the variable in the property window, which can be used to select an actor from the UnrealEd viewports. For obvious reasons this only makes sense for variables of type Actor or any of its subclasses.
; EditConst<sup>S</sup>: The variable is read-only in the property window.
; EditConstArray<sup>S,2</sup>, editfixedsize<sup>S,3</sup>: For dynamic arrays, removes the buttons from the properties window that would change the array length.
; EditHIde<sup>S,3+</sup>: Hide in [[UnrealEd]] property lists.{{confirm}}
; EditInline<sup>S,2,3</sup>: Only meaningful for object variables. Displays the referenced object's properties as a subgroup below the variable in the property window. If the variable has the value None, a drop-down list of allowed ([[editinlinenew]], non-[[abstract]]) classes can be used to create a new object which is assigned to this variable.
; EditInlineUse<sup>S,2,3</sup>: Same as '''editinline''', but also adds a 'Use' button to the variable to apply the object selected in the relevant browser for this type of object. Note that the 'Use' button is always available in [[Unreal Engine 3]].
; EditorOnly<sup>3+</sup>: The variable value is only loaded for [[UnrealEd]].
; EditorTextBox<sup>S?,3+</sup>: Replaces the usual input box with a button for opening a separate dialog with a multi-line text box for entering. Probably only useful for [[string]] variables.
; Interp<sup>3</sup>: The variable can be manipulated by [[Unreal Engine 3]]'s [[Matinee]] system. Only really meaningful for float and vector variables.
; NoClear<sup>S,3</sup>: Instructs the editor to prevent the user from setting this variable to None. Only really meaningful for object variables.
; NoImport<sup>S,3</sup>: The variable's value will not be imported from text representation, i.e. when importing from a [[T3D file]] or pasting from clipboard.
; NonTransactional<sup>S,3</sup>: The variable is not affected by UnrealEd's undo/redo features.
; SerializeText<sup>3+</sup>: Variable will not be saved, but will be transfered during copy-paste operations (which are done through text). Works only on native variables.
::''Requirements'': '''Native'''


<uscript>var() int MyInteger; // Declare an editable integer in the default category.
===Other modifiers===
var(MyCategory) bool MyBool; // Declare an editable integer in "MyCategory".</uscript>
The following modifiers don't really fit into any of the above categories.
; cache<sup>UT2004</sup>: Marks properties of certain classes that should be included in [[UCL file]] entries for that class. This is used e.g. for weapon and mutator names and descriptions.
; editinlinenotify<sup>S,2</sup>: Seems to provide special feedback to native code if the variable is edited in a property window. Seems only relevant for native classes and implies '''editinline'''.
; export<sup>S,2,3</sup>: For object properties. Objects assigned to this variable are exported as subobjects when exporting class scripts or when exporting actors to [[T3D file]]s or clipboard.
; init<sup>S,3</sup>: Changes the way string and dynamic array variables are exported to headers for native classes. Default values for this kind of variable are ignored when creating instances of the class.
; native: The variable is loaded and saved in native code. Only valid in native classes.
; noexport<sup>S,2,3</sup>: Prevents the variable's value from being exported when exporting class scripts or when exporting actors to [[T3D file]]s or clipboard.
; notforconsole<sup>3+</sup>: The variable value is discarded on console platforms.
; repretry<sup>3+</sup>: If replication of this variable was not successful the replication will be tried again.
; repnotify<sup>3</sup>: Can be used on replicated actor variables to instruct the engine to call the [[UE3:Actor events (UT3)#ReplicatedEvent|ReplicatedEvent]] function whenever a value was received for the variable.


== Object and actor reference variables ==
===Modifiers with unknown effect===
The effects of these modifiers are not known yet.
; Archetype<sup>3</sup>: Effect unknown. Used only for the [[UE3:UIPrefabInstance (UT3)#SourcePrefab|UIPrefabInstance.SourcePrefab]] variable in UT3.
; CrossLevelActive<sup>3+</sup>: See below.
; CrossLevelPassive<sup>3+</sup>: Probably related to level streaming or multiple levels loaded at the same time.


You can declare a variable that refers to an actor or object like this:
==Initial values==
The initial values of class variables can be specified in the [[defaultproperties]] block. The initial value can be different in subclasses without affecting the value of parent classes. Some class variables, for example Name, Outer, Tag or Location, are initialized with other values when an instance of the class is created.


<uscript>var actor A; // An actor reference.
Initial values of struct members can be specified in thee [[structdefaultproperties]]. In structs that extend other structs, the initial value can differ from the value in the parent struct. Since structs are data types and only exist as values of other variables, initial member values for those variables may differ from the default struct member value.
var pawn P; // A reference to an actor in the Pawn class.
var texture T; // A reference to a texture object.</uscript>


The variable "P" above is a reference to an actor in the Pawn class. Such a variable can refer to any actor that belongs to a subclass of Pawn. For example, P might refer to a Brute, or a Skaarj, or a Manta. It can be any kind of Pawn. However, P can never refer to a Trigger actor (because Trigger is not a subclass of Pawn).
The initial value of a local variable is always the null value for the declared variable [[type]]. The initial value for function parameters is the value passed in when the function is called. Omitted optional parameters initially contain the type's null value. In [[Unreal Engine 3]] it is also possible to specify a different initial value for omitted optional parameters.


One example of where it's handy to have a variable refering to an actor is the Enemy variable in the Pawn class, which refers to the actor which the Pawn is trying to attack.
==Accessing variables==
Class variables can be accessed directly by just specifying their name from instance functions, state code or the [[replication block]] inside the declaring class or any of its subclasses.


When you have a variable that refers to an actor, you can access that actor's variables, and call its functions. For example:
The default value for a class variable can be accessed directly by using the keyword '''default''' and the context operator '.' from anywhere inside the class, including static functions:
'''default.'''variablename
The default value of another class can be accessed by providing a different class context to the '''default''' keyword:
objectreference'''.default.'''variablename
The object reference can be an [[Literals#Objects|object literal]] or an object reference variable. If the type of the object reference is a Class or a [[class limiter]], that class is used, otherwise the referenced object's class type is used to access the default variable value. When using an object literal is usually doesn't make sense to use a non-class literal because you usually know the class of the referenced object and the engine really doesn't care about the actual object if it is only interested in the class anyway.


<uscript>// Declare two variables that refer to a pawns.
Struct member variables and class variables of other classes or other instances of the same class can be accessed with the context operator '.', like in the following example:
var pawn P, Q;
<uscript>
 
function float getX(vector V)
// Here is a function that makes use of P.
// It displays some information about P.
function MyFunction()
{
{
// Set P's enemy to Q.
  return V.X;
P.Enemy = Q;
}
 
</uscript>
// Tell P to play his running animation.
This accesses the struct member variable ''X'' of the vector value passed to the function as parameter ''V''. The parameter ''V'' is a local variable to the function ''getX''. Local variables can only be accessed inside their containing function.
P.PlayRunning();
}</uscript>


Variables that refer to actors always either refer to a valid actor (any actor that actually exists in the level), or they contain the value "None". None is equivalent to the C/C++ "NULL" pointer. However, in UnrealScript, it is safe to access variables and call functions with a "None" reference; the result is always zero.
Variables accessed as described in this section can be used as an [[wp:lvalue|L-value]], i.e. used on the left side of an assignment operator or as an [[out]] parameter in a function call.


Note that an object or actor reference "points to" another actor or object, it doesn't "contain" an actor or object. The C equivalent of an actor reference is a pointer to an object in the AActor class (in C, you'd say an AActor*). For example, you could have two monsters in the world, Bob and Fred, who are fighting each other. Bob's "Enemy" variable would "point to" Fred, and Fred's "Enemy" variable would "point to" Bob.
{{navbox unrealscript}}
 
Unlike C pointers, UnrealScript object references are always safe and infallible. It is impossible for an object reference to refer to an object that doesn't exist or is invalid (other than the special-case "None" value). In UnrealScript, when an actor or object is destroyed, all references to it are automatically set to "None".
 
== Class Reference Variables ==
 
In Unreal, classes are objects just like actors, textures, and sounds are objects.  Class objects belong to the class named "class".  Now, there will often be cases where you'll want to store a reference to a class object, so that you can spawn an actor belonging to that class (without knowing what the class is at compile-time).  For example:
 
<uscript>var() class C;
var actor A;
A = Spawn( C ); // Spawn an actor belonging to some arbitrary class C.</uscript>
 
Now, be sure not to confuse the roles of a class C, and an object O belonging to class C.  To give a really shaky analogy, a class is like a pepper grinder, and an object is like pepper.  You can use the pepper grinder (the class) to create pepper (objects of that class) by turning the crank (calling the Spawn function)...BUT, a pepper grinder (a class) is not pepper (an object belonging to the class), so you '''MUST NOT TRY TO EAT IT!'''
 
When declaring variables that reference class objects, you can optionally use the special class<classlimitor> syntax to limit the variable to only containing references to classes which expand a given superclass.  For example, in the declaration:
 
<uscript>var class<actor> ActorClass;</uscript>
 
The variable ActorClass may only reference a class that expands the "actor" class.  This is useful for improving compile-time type checking.   For example, the Spawn function takes a class as a parameter, but only makes sense when the given class is a subclass of Actor, and the class<classlimitor> syntax causes the compiler to enforce that requirement.
 
As with dynamic object casting, you can dynamically cast classes like this:
 
<uscript>class<actor>( SomeFunctionCall() )</uscript>
 
== Enumerations ==
 
Enumerations exist in UnrealScript as a convenient way to declare variables that can contain "one of" a bunch of keywords. For example, the actor class contains the enumeration EPhysics which describes the physics which Unreal should apply to the actor. This can be set to one of the predefined values like PHYS_None, PHYS_Walking, PHYS_Falling, and so on.
 
Internally, enumerations are stored as byte variables. In designing UnrealScript, enumerations were not seen as a necessity, but it makes code so much easier to read to see that an actor's physics mode is being set to "PHYS_Swimming" than (for example) "3".
 
Here is sample code that declares enumerations.
 
<uscript>// Declare the EColor enumeration, with three values.
enum EColor
{
CO_Red,
CO_Green,
CO_Blue
};
 
// Now, declare two variables of type EColor.
var EColor ShirtColor, HatColor;
 
// Alternatively, you can declare variables and
// enumerations together like this:
var enum EFruit
{
FRUIT_Apple,
FRUIT_Orange,
FRUIT_Bannana
} FirstFruit, SecondFruit;</uscript>
 
In the Unreal source, we always declare enumeration values like LT_Steady, PHYS_Falling, and so on, rather than as simply "Steady" or "Falling". This is just a matter of programming style, and is not a requirement of the language.
 
UnrealScript only recognizes unqualified enum tags (like FRUIT_Apple) in classes where the enumeration was defined, and in its subclasses.  If you need to refer to an enumeration tag defined somewhere else in the class hierarchy, you must "qualify it":
 
<uscript>FRUIT_Apple // If Unreal can't find this enum tag...
EFruit.FRUIT_Apple // Then qualify it like this.</uscript>
 
== Structs ==
 
An UnrealScript struct is a way of cramming a bunch of variables together into a new kind of super-variable called a struct. UnrealScript structs are just like C structs, in that they can contain any simple variables or arrays.
 
You can declare a struct as follows:
<uscript>// A point or direction vector in 3D space.
struct Vector
{
var float X;
var float Y;
var float Z
};</uscript>
 
Once you declare a struct, you are ready to start declaring specific variables of that struct type:
 
<uscript>// Declare a bunch of variables of type Vector.
var Vector Position;
var Vector Destination;</uscript>
 
To access a component of a struct, use code like the following.
 
<uscript>function MyFunction()
{
Local Vector A, B, C;
 
// Add some vectors.
C = A + B;
 
// Add just the x components of the vectors.
C.X = A.X + B.X;
 
// Pass vector C to a function.
SomeFunction( C );
 
// Pass certain vector components to a function.
OtherFunction( A.X, C.Z );
}</uscript>
 
You can do anything with Struct variables that you can do with other variables: you can assign variables to them, you can pass them to functions, and you can access their components.
 
There are several Structs defined in the Object class which are used throughout Unreal. You should become familiar with their operation, as they are fundamental building blocks of scripts:
 
* Vector: A unique 3D point or vector in space, with an X, Y, and Z component.
* Plane: Defines a unique plane in 3D space. A plane is defined by its X, Y, and Z components (which are assumed to be normalized) plus its W component, which represents the distance of the plane from the origin, along the plane's normal (which is the shortest line from the plane to the origin).
* Rotation: A rotation defining a unique orthogonal coordinate system. A rotation contains Pitch, Yaw, and Roll components.
* Coords: An arbitrary coordinate system in 3D space.
* Color: An RGB color value.
* Region: Defines a unique convex region within a level.

Latest revision as of 09:51, 16 September 2015

Variables are named storage slots for pieces of data. All UnrealScript variables are staticly-typed, that means you can only store a specific type of data in them and the type of data is defined in the variable declaration.

There are three basic types of variables in UnrealScript:

  • Class variables, which can only be declared at the class scope, before any function, operator, delegate or state declaration.
  • Struct members, which are declared inside their struct's declaration block.
  • Local variables, which can be declared at the start of function, state, operator and delegate bodies before any code statements. (For readability's sake, this article will imply operators and delegates when it mentions functions, unless otherwise noted.)

Declaration

A simple class or struct member variable declaration looks like this:

var [modifiers] type variablename;

The variablename can be any combination of the letters A-Z (case-insensitive), the digits 0-9 and the underscore character _ with two restrictions:

  • The name may not start with a digit.
  • The name must be shorter than 64 characters.

The type can not only be a type specification, but also a struct or enum declaration.

You can declare multiple variables of the same type in one declaration:

var [modifiers] type variablename1, variablename2, ...;

Each of the variable names may optionally have an array size specification to create a static array:

variablename[arraysize]

You can mix static arrays and non-array variables in a single declaration. The array size only applies to the variable you appended it to.

Editable variables

To make the variable accessible from within UnrealEd's property windows, use the following syntax:

var([groupname[,subgroup3]]) [modifiers] type variablename;

The groupname must be an identifier if specified. If omitted, the class name is used as group name. For struct members, the group name has no effect.

Local variables

Local variable declarations in function bodies are similar, but a bit simpler:

local type variablename;

Local variables must be declared at the very top of the function body, between the { and the first line of "executable" code.

You can declare static arrays and multiple variables of the same type as described for class and struct variables above. The type must be an existing type. It is not allowed to declare new structs or enums here.

After declaration, a local variable is initially null, which can mean different things, depending on the variable type. (Zero for numeric types, False, empty string or array, None, etc.)


Note: As of UDK 2011-06+?[confirm] it is also possible to declare local variables in states. Local variables must be declared before ignores.

Modifiers

For class and struct variables you are allowed to specify one or more variable modifiers. These change the way the variable works in certain situations.

The modifier is available in ...
Version Tag Game Engine Version
1 Any Unreal Engine 1 game e.g. UT Unreal Engine 1
2 Any Unreal Engine 2 game e.g. UT2004 Unreal Engine 2
3 Any Unreal Engine 3 game e.g. UT3 Unreal Engine 3
3-x1 UT3 patch 2.0 Unreal Engine 3
3-x2 UDK 2009-12 Unreal Engine 3 - 6000 - present
3-x3 UDK 2010-07 Unreal Engine 3 - 6890 - present
(lesser than i.e. <) A specific version e.g. 3 < 3-x2 would mean it's available in Unreal Engine 3 but not anymore since UDK
(no number) all Unreal Engine generations.

Modifiers tagged with S can be used for struct members.

Inner type modifiers

You can also specify variable modifiers for the inner type of a dynamic array declaration. This compiler feature is available in all engine versions, but doesn't have any effect before Unreal Engine 3. The only currently known instances of this are several variables in two classes of the UDK's Engine package (NxForceField and NxGenericForceFieldBrush, both using array<const native transient pointer>), so this feature might only work at all in newer versions of Unreal Engine 3. Note: All inner modifiers are as well implicity added to the variable modifiers, so for example if you were to add EditConst the actual variable would as well act upon EditConst.

Access modifiers

The following modifiers only apply to class variables and specify, which other classes are allowed to access the variable. The access rules are enforced by the compiler.

ConstS
Prevents any changes to this variable from within UnrealScript. You are still allowed to specify a value in the defaultproperties block and access the variable's value in your code. This property is mostly used to protect variables with a special meaning to native code. Classes with const variables usually have a corresponding setter function for each variable. With bytecode level hacking, it's possible to assign a value to a const variable, but in general, the effect is undefined (ranging from giving the result you want to crashing the game).
Deprecated2,3
Signals that this variable should no longer be used. Accessing deprecated variables will throw a compiler warning. Unreal Engine 3 will load the value of a deprecated variable, but ignore it during save.
PrivateS,2,3
Private variables can only be accessed from within the class they were declared in. Other classes, even subclasses, can't access them.
PrivateWrite3-x2
Related to the private access modifier. Causes the variable to be treated as private for writing, but public for reading.
ProtectedS,2,3
Access to protected variables is only allowed from within the same class and its subclasses. Sibling classes, parent classes and other, unrelated classes can't "see" protected variables.
ProtectedWrite3-x2
Related to the protected access modifier. Causes the variable to be treated as protected for writing, but public for reading.
PublicS,2,3
The default access rule. If no other access rule is specified, this is one is implied. Public variables can be accessed from any other class. Usually you will see this modifier in Unreal Engine 3, along with a native code snippet. One of the most common examples is public{private}, which means the variable is declared as public for UnrealScript, but as private for native code.

Modifiers affecting values

These modifiers affect the default value of the variable in some way.

AutomatedUT2004
Only meaningful for object variables in GUIMultiComponent classes. Indicates that any GUIComponent object(s) referenced by this variable should automatically be added to the Controls array. Also works for static and dynamic arrays. Objects that aren't GUIComponents are ignored.
Implies: noexport, editinline, editinlineuse and editinlinenotify, and FYI: any object variable(even parameters and locals) referencing GUIComponents implies export and editinline.
ConfigS
Makes the variable configurable. The default variable value is read from an INI file when the class is loaded. Each subclass has its own version of the variable value in its INI file section. If the class is declared with the PerObjectConfig modifier, the initial instance value of the variable is read from a separate INI section for that object instance.
DataBinding3
The variable can be manipulated by Unreal Engine 3's data store system.
DuplicateTransient3
Similar to transient (see below) but applies to object duplication.
GlobalConfigS
Similar to the config modifier, but a globalconfig variable's default value is always read from the INI section of its declaring class, even for subclasses.
Implies: config
Input
Attaches the variable to the input system. This is only meaningful for float and byte variables, which can be tied to axis and button input respectively. Input variables are only filled for the local player actor.
Instanced3
Only meaningful for reference variables. Subobjects assigned to instanced variables are duplicated when an instance of the class is created.
Implies: export and editinline even on non-reference variables.
LocalizedS
Makes the variable localizable. The default value of the variable is read from a localization file when the class is loaded. Each subclass can have its own localized versions of the variable value. In Unreal Engine 1 and 2 and if the class is declared as PerObjectLocalized in Unreal Engine 3, each instance of the class can have its own set of localized variable values. This is useful for actors placed in a map.
Implies: const3
TransientS
The variables is set to its null value when initializing object instances. The variable's value is never saved to disk in any way.
Travel1,2
For single player gametypes where a player advances from one map to the next, carrying over all inventory items. Instance variables marked as travel will keep their value across the map change. Only has an effect for the PlayerPawn in UE1 (or the PlayerController and its Pawn in UE2) and its Inventory chain.

Modifiers affecting UnrealEd

These modifiers have some kind of effect in UnrealEd, usually in the actor properties window.

EdFindableS,2
Adds a 'Find' button to the variable in the property window, which can be used to select an actor from the UnrealEd viewports. For obvious reasons this only makes sense for variables of type Actor or any of its subclasses.
EditConstS
The variable is read-only in the property window.
EditConstArrayS,2, editfixedsizeS,3
For dynamic arrays, removes the buttons from the properties window that would change the array length.
EditHIdeS,3+
Hide in UnrealEd property lists.[confirm]
EditInlineS,2,3
Only meaningful for object variables. Displays the referenced object's properties as a subgroup below the variable in the property window. If the variable has the value None, a drop-down list of allowed (editinlinenew, non-abstract) classes can be used to create a new object which is assigned to this variable.
EditInlineUseS,2,3
Same as editinline, but also adds a 'Use' button to the variable to apply the object selected in the relevant browser for this type of object. Note that the 'Use' button is always available in Unreal Engine 3.
EditorOnly3+
The variable value is only loaded for UnrealEd.
EditorTextBoxS?,3+
Replaces the usual input box with a button for opening a separate dialog with a multi-line text box for entering. Probably only useful for string variables.
Interp3
The variable can be manipulated by Unreal Engine 3's Matinee system. Only really meaningful for float and vector variables.
NoClearS,3
Instructs the editor to prevent the user from setting this variable to None. Only really meaningful for object variables.
NoImportS,3
The variable's value will not be imported from text representation, i.e. when importing from a T3D file or pasting from clipboard.
NonTransactionalS,3
The variable is not affected by UnrealEd's undo/redo features.
SerializeText3+
Variable will not be saved, but will be transfered during copy-paste operations (which are done through text). Works only on native variables.
Requirements: Native

Other modifiers

The following modifiers don't really fit into any of the above categories.

cacheUT2004
Marks properties of certain classes that should be included in UCL file entries for that class. This is used e.g. for weapon and mutator names and descriptions.
editinlinenotifyS,2
Seems to provide special feedback to native code if the variable is edited in a property window. Seems only relevant for native classes and implies editinline.
exportS,2,3
For object properties. Objects assigned to this variable are exported as subobjects when exporting class scripts or when exporting actors to T3D files or clipboard.
initS,3
Changes the way string and dynamic array variables are exported to headers for native classes. Default values for this kind of variable are ignored when creating instances of the class.
native
The variable is loaded and saved in native code. Only valid in native classes.
noexportS,2,3
Prevents the variable's value from being exported when exporting class scripts or when exporting actors to T3D files or clipboard.
notforconsole3+
The variable value is discarded on console platforms.
repretry3+
If replication of this variable was not successful the replication will be tried again.
repnotify3
Can be used on replicated actor variables to instruct the engine to call the ReplicatedEvent function whenever a value was received for the variable.

Modifiers with unknown effect

The effects of these modifiers are not known yet.

Archetype3
Effect unknown. Used only for the UIPrefabInstance.SourcePrefab variable in UT3.
CrossLevelActive3+
See below.
CrossLevelPassive3+
Probably related to level streaming or multiple levels loaded at the same time.

Initial values

The initial values of class variables can be specified in the defaultproperties block. The initial value can be different in subclasses without affecting the value of parent classes. Some class variables, for example Name, Outer, Tag or Location, are initialized with other values when an instance of the class is created.

Initial values of struct members can be specified in thee structdefaultproperties. In structs that extend other structs, the initial value can differ from the value in the parent struct. Since structs are data types and only exist as values of other variables, initial member values for those variables may differ from the default struct member value.

The initial value of a local variable is always the null value for the declared variable type. The initial value for function parameters is the value passed in when the function is called. Omitted optional parameters initially contain the type's null value. In Unreal Engine 3 it is also possible to specify a different initial value for omitted optional parameters.

Accessing variables

Class variables can be accessed directly by just specifying their name from instance functions, state code or the replication block inside the declaring class or any of its subclasses.

The default value for a class variable can be accessed directly by using the keyword default and the context operator '.' from anywhere inside the class, including static functions:

default.variablename

The default value of another class can be accessed by providing a different class context to the default keyword:

objectreference.default.variablename

The object reference can be an object literal or an object reference variable. If the type of the object reference is a Class or a class limiter, that class is used, otherwise the referenced object's class type is used to access the default variable value. When using an object literal is usually doesn't make sense to use a non-class literal because you usually know the class of the referenced object and the engine really doesn't care about the actual object if it is only interested in the class anyway.

Struct member variables and class variables of other classes or other instances of the same class can be accessed with the context operator '.', like in the following example: <uscript> function float getX(vector V) {

 return V.X;

} </uscript> This accesses the struct member variable X of the vector value passed to the function as parameter V. The parameter V is a local variable to the function getX. Local variables can only be accessed inside their containing function.

Variables accessed as described in this section can be used as an L-value, i.e. used on the left side of an assignment operator or as an out parameter in a function call.