UnityScript Keywords
(→yield) |
|||
Line 193: | Line 193: | ||
The most common use of the extends keyword is when we want to create a class with access to the basic script events along with accessors to other stuff (GetComponent, etc). To achieve this we write | The most common use of the extends keyword is when we want to create a class with access to the basic script events along with accessors to other stuff (GetComponent, etc). To achieve this we write | ||
<syntaxhighlight lang="javascript">class myClass extends MonoBehaviour { //your code }</syntaxhighlight> | <syntaxhighlight lang="javascript">class myClass extends MonoBehaviour { //your code }</syntaxhighlight> | ||
+ | |||
+ | ===false=== | ||
===finally=== | ===finally=== | ||
Line 342: | Line 344: | ||
print(FunctionThatReturnsAString()); // Result: "Hello" appears in the console log</syntaxhighlight> | print(FunctionThatReturnsAString()); // Result: "Hello" appears in the console log</syntaxhighlight> | ||
+ | |||
+ | ===sbyte=== | ||
===short=== | ===short=== | ||
Line 364: | Line 368: | ||
This is analogous to having global variables and functions, but their names are contained by the script in which they're declared, so you can have separate ThisScript.something and ThatScript.something variables without a conflict. | This is analogous to having global variables and functions, but their names are contained by the script in which they're declared, so you can have separate ThisScript.something and ThatScript.something variables without a conflict. | ||
+ | |||
+ | ===string=== | ||
===super=== | ===super=== | ||
Line 403: | Line 409: | ||
The throw statement throws an exception to indicate an error has occurred | The throw statement throws an exception to indicate an error has occurred | ||
+ | ===true=== | ||
===try=== | ===try=== | ||
===typeof=== | ===typeof=== | ||
Line 412: | Line 419: | ||
*function | *function | ||
*undefined | *undefined | ||
+ | |||
+ | ===uint=== | ||
+ | ===ulong=== | ||
+ | ===ushort=== | ||
===var=== | ===var=== | ||
Line 427: | Line 438: | ||
var myVar : Type = new Type();</syntaxhighlight> | var myVar : Type = new Type();</syntaxhighlight> | ||
Javascript supports both dynamic typing and static typing. For max efficiency you should not use pure dynamic typing. To disable dynamic typing in a certain file, type "#pragma strict". | Javascript supports both dynamic typing and static typing. For max efficiency you should not use pure dynamic typing. To disable dynamic typing in a certain file, type "#pragma strict". | ||
+ | |||
+ | ===virtual=== | ||
+ | ===void=== | ||
===while=== | ===while=== |
Revision as of 12:00, 24 March 2013
as
TODO
boolean
The boolean keyword is used to is used to define a variable of type boolean . A boolean variable can hold either the value of true or false.
var alive : boolean; function Start(){ alive = true; if (alive == true){ print("player is alive"f); } }
One advantage of using a boolean over an integer of value 0 or 1 is that a boolean can be toggled without knowing what state it is in at the moment. Example: Switching a light on and off by pressing the same button.
public var light_state : boolean; // we don't know the value of light_state function toggleLight() { light_state = !light_state; // if the light was off, it's on now, and vice versa. }
break
The break keyword is used to skip the execution of and any remaining iterations of the body of a
- while loop.
- for loop.
- switch statement.
See also while, for and switch keywords for more info and examples.
byte
The byte keyword is used to define a variable of type byte. The byte variables can take any integer values from 0 to 255. It corresponds to the System.Byte (see MSDN).
var myByte : byte; function Start(){ myByte = 8 ; print(myByte.ToString()); }
The sbyte is not a keyword. If someone needs the sbyte value type can access it using System.SByte
import System; var myByte : System.SByte; function Start(){ myByte = -8 ; print(myByte.ToString()); }
case
See the switch keyword for more info and examples.
catch
The catch keyword is a statement used in a try-catch or try-catch-finally exception handling structure. The catch expression is used to catch runtime exceptions during execution time, and execute some code if exceptions are cought. For more information on exceptions look for the keywords System Exception Class in MSDN. More info and examples in the try keyword
char
The char keyword is used to define a variable of type char. Char variables contain one Unicode character. Unicode characters range from '\u0000' to '\uffff' and are used to display alphanumeric characters and symbols. You cannot assign a value like in other languages
var fisrtLetter : char; fisrtLetter = 'I'; // does NOT work.
You can use the following hack, though:
var firstLetter : char; function Start(){ firstLetter = "g"[0]; print (firstLetter); }
class
The class keyword is used for defining a class (classes are an Object-Oriented Programming feature). The class is a blueprint for objects; i.e. it describes what properties (think of properties as variables) and methods (think them as functions) a new object of this class has. Lets make a class "Woman" (classes should always begin with a capital letter). The Woman object will have
- two properties: name, hair color
- one method: talk
class Woman { // This is the constructor of the class. It takes arguments like // myhairColor and myName and passes them as class properties function Woman (myHairColor : String, myName : String) { this.hairColor = myHairColor; this.name = myName; } // Here are some class properties var name : String; var hairColor : String; // Here is a class method function talk (content : String) { print(content); } } function Start(){ // Here we initialize a new Woman object with arguments myhairColor=black // and myName = Mary var Mary = new Woman("black", "Mary"); // Here we use the talk() method of the Mary object Mary.talk("Hi. My name is " + Mary.name + " and my hair is " + Mary.hairColor + "."); }
continue
The continue keyword is a jump statement. It skips the following statements in the loop and makes an early start on the next iteration.
// In this example the continue statement forces unity to "skip" // the iterations where the condition (i%2)==0 is true, ie the even numbers var i:int; function Start () { for (i = 0; i < 10; i++){ // The condition (i % 2) == 0 s true when i is even if ((i % 2) == 0) continue; // The console output will be 1 3 5 7 9 because the even values of i are skipped print(i + " "); } }
Lets see what happens if we remove the continue statement
// Here we removed the continue statement and as a result the script will only // output on those iterations where the condition (i%2)==0 is true, ie the even numbers var i:int; function Start () { for (i = 0; i < 10; i++){ // The condition (i % 2) == 0 s true when i is even if ((i % 2) == 0) { // The console output will be 0 2 4 6 8 print(i + " "); } } }
default
See the switch keyword for more info and examples.
do
Used in do-while loops.
double
The double keyword is used to define a variable of type double. Unlike C#, a numeric literal (eg 3) is not denoted as a double with a suffix (in C# is d or D).
var myDouble : double; function Start(){ myDouble = 8321.2 ; print(myDouble.ToString()); }
else
See the documentation for the if keyword.
enum
An enum (short for enumeration) is a special datatype that lets you specify a group of named numeric constants. By default, the constants 0, 1, 2… are automatically assigned in the declaration order of the enum members; 0 is assigned to the first member, 2 to the second, etc. There are several advantages to using this structure over strings or plain integers:
- Strings take up more memory.
- Integers [as well as other number types] can and usually do take up more memory than necessary for an enum.
- Strings require validation (typos when referencing named values of an enum are easily caught at compile-time).
// The code below means "assign GameDifficulty.Easy to 0, GameDifficulty.Moderate to 1 etc" enum GameDifficulty { Easy, Moderate, Hard, Insane }; function Start(){ // In a real-life situation this can be selected via a GUI var myGame = GameDifficulty.Moderate; switch (myGame){ // The code below is equivalent to "case GameDifficulty.Easy:" case 0: print("Set in easy mode"); break; case 1: print("Set in moderate mode"); break; case 2: print("Set in hard mode"); break; case 3: print("Set in insane mode"); break; } }
extends
The extends keyword is used when a class is declared to inform the compiler that this class inherits from another class. This allows the programmer to reuse the functionality of a known class. A class inherits from one class only (superclass->myClass) but can be inherited by many classes (myClass->subclass1, myClass->subclass2 etc).
The most common use of the extends keyword is when we want to create a class with access to the basic script events along with accessors to other stuff (GetComponent, etc). To achieve this we write
class myClass extends MonoBehaviour { //your code }
false
finally
The finally keyword is used after a catch block for code that should be executed regardless of whether the catch triggered or not. See the documentation for the try keyword.
float
The float keyword is used to define a variable of type float. (e.g 1.0, 1.24325, 1283.02349 or -1283.02349).
for
A for statement is a type of loop, the normal for statement has 3 parts, however when used with the in keyword (see the documentation for the in keyword) it only has 1 part. The format for a normal for statement is something like this:
- for (declarations;conditions;increments) { ... }
A declaration might be something like var i = 0; or i = 32; or var bobsName = "NameHere". A condition might be something like i < 32 (which would mean do this loop as long as i is smaller then 32). and a increment might be something like ++i; or i=i+323;
function
The function keyword is used to create functions (if you come from a pure Object-Oriented background, functions in javascript are basically methods). Functions will execute a certain "block" of code. They can have parameters, the can return values, and they can be specific to certain classes. Here are the various function formats.
function FunctionName() { ... } function FunctionName(param : paramType) { ... } (note, you can have as many parameters as you want...) function FunctionName() : returnType { ... } function FunctionName(param : paramType) : returnType { ... }
When a function encounters a return statement, it does 2 things:
- First thing, it checks to see if there is a variable, or constant c, that comes directly after the return statement (e.g return someVariable;). If it does, it will return that variable. Example, lets say we have a function called Return4(), and lets say that it returns 4 (return 4;). We could do something like this:
var myVar : int = Return4(); //myVar would then equal 4.
- The second thing that happens when the function encounters a return statement, is it stops executing the code in the function.
if
The if statement selects a statement for execution based on the value of a Boolean expression. It takes the following form:
if (expression){ statement1; } else{ statement2; }
It is good practice to place the statements inside curly braces. This ensures that there is no ambiguity as to where the statement starts and ends. With nested if else blocks it also makes it clear which else is associated with which if. Finally, it makes it easy to add more statements! For example:
if (expression1){ if (expression2){ statement1; statement2; } } else{ statement3; }
import
Gives access to a namespace.
in
The in keyword is used in for loops as a short-cut for going through an array. In a in based for loop, there are 2 variables needed. 1 variable being the array itself, and the other being a variable that will be assigned as the value of the current selection of the array variable.
var array : Array = new Array ("v1", "v2", "v3"); for (var tmp : String in array) { print (tmp); }
An alternate way of writing this (without a in statment) would be like this.
var array : Array = new Array("v1", "v2", "v3"); var i : int = 0; for (var tmp : String; i < array.length; tmp = array[i]) { print (tmp); ++i; }
As you can see, using the in form of a for loop eliminates the need for a count variable. Obviously a in form for statment shouldn't be used for everything, however, if you are going through a large array of objects, and are purely changing properties of those objects, or reading the data in those objects, the in keyword can be quite useful.
instanceof
Used to check whether an object is of a given type. The equivalent keyword in C# is the "is" keyword.
class _paddle { } class _paddle2 { } function Start(){ var player1Paddle = new _paddle2(); if (player1Paddle instanceof _paddle){ print("yes it is"); } else{ print("no it is not"); } }
int
Declare and initalise a variable of type int, a signed 32-bit integer. Range :-2^31 through (2^31)-1. Unsigned int's (uint datatype) are not supported. Long (64 bit version of int) and short (16 bit version) of int's are supported. Look at their documentation below. Actually, int is just a keyword which maps to System.Int32
long
new
The new keyword is used with certain types of classes to allocate the memory needed to use them. Here is an example.
var myArray : Array = new Array("v1", "v2");
Usually if you create your own model classes you will have to use the new keyword when creating a variable of that model class, otherwise you will get a null reference error.
null
The keyword null, is a nonexistant value. It can be assigned to a variable, or used to test whether a variable has a value.
var something = null; if(something == null) { print("something is null!"); }
You could also write the if statement like this to implicitly test for null:
if(something) { print("something is null!"); }
References to Unity's GameObjects, Components and the like are marked as null as soon as they have been destroyed, so this is a good way to check that something still exists before you try to access its members.
private
The private keyword should be used in a format such as:
private var tmp;
Variables and functions marked as private can only be accessed by the class that declares them. On top of that, in Unity, you cannot see private variables in the editor (unless the editor is set to debug mode).
protected
Similar to private, but permits extending classes to access the variable or function.
public
This is the other extreme of the private-protected-public triad. Public variables and functions can be accessed by code outside of the class and hierarchy in which they were defined. This is the default state, so the public keyword is completely optional.
return
Returns a value from a function.
function FunctionThatReturnsAString() { return "Hello"; } print(FunctionThatReturnsAString()); // Result: "Hello" appears in the console log
sbyte
short
The short keyword is used to define a variable of type short. Short is an integer (ie no decimals are allowed). Range of short: –32,768 through 32,767.
static
Lets you declare a variable or function that can be accessed using only the class name instead of via a reference to a specific object.
For example, if you have a script files named SomeScript.js with these contents:
static var something = 10; static function SomeFunction() { print("SomeFunction called"); }
You can access those members like this from any other script:
SomeScript.something = 20; SomeScript.SomeFunction();
This is analogous to having global variables and functions, but their names are contained by the script in which they're declared, so you can have separate ThisScript.something and ThatScript.something variables without a conflict.
string
super
The super keyword is used in functions to directly manipulate the superclass of the class that owns the function.
switch
The switch statement is a type of conditional statement.
switch(i) { case 0: // this block of code is executed if i == 0 break; case 1: // this block of code is executed if i == 1 break; default: // executed if none of the above }
First there is the actual "switch" keyword. Along with this is a variable (in this case i). Then are curly braces. Inside the curly braces, is a series of case statements. A case statement works like this.
switch(i)
If the variable you provided in the switch statement is equal to the value you provided in the case statement, the code inbetween the case statement and the break statement will be executed. If the value provided in the case statement is not equal to the variable provided in the switch statement, it moves on to the next case statement. If none of the cases cover the actual value of the provided variable, it will go to the default statement, and execute the code inside.
case 4: // if i equals 4 then this block of code is executed break;
this
The this keyword is used in class function to directly manipulate instance variables, or to call functions.
throw
The throw statement throws an exception to indicate an error has occurred
true
try
typeof
The typeof keyword (used like "typeof(variable)") will return a string. The string will be
- number
- string
- boolean
- object
- function
- undefined
uint
ulong
ushort
var
var is used to declare variables. Here are some of the formats for using var.
var myVar; var myVar : Type; var myVar = value; var myVar : Type = value; var myVar = new Type(); var myVar : Type = new Type();
Javascript supports both dynamic typing and static typing. For max efficiency you should not use pure dynamic typing. To disable dynamic typing in a certain file, type "#pragma strict".
virtual
void
while
The while statement is a loop statement that takes a conditional statement, and while the conditional statement is true, the code in the while loop will be executed. The format for a while statment is
while (condition) { ... }
yield
Used in coroutines.