UnityScript Keywords

From Unify Community Wiki
(Difference between revisions)
Jump to: navigation, search
(static)
(Expanded on 'static', then got sucked into clarifying a bunch of other stuff. Still needs a lot of work)
Line 174: Line 174:
 
===extends===
 
===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 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).  
<javascript>
+
 
</javascript>
+
 
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  
<javascript>class myClass extends MonoBehaviour { //your code }
+
<javascript>class myClass extends MonoBehaviour { //your code }</javascript>
</javascript>
+
<javascript>
+
</javascript>
+
  
 
===finally===
 
===finally===
Line 260: Line 256:
 
}
 
}
 
</javascript>
 
</javascript>
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 usefull.
+
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.
  
===int===
 
 
===instanceof===
 
===instanceof===
 
Used to check whether an object is of a given type. The equivalent keyword in C# is the "is" keyword.
 
Used to check whether an object is of a given type. The equivalent keyword in C# is the "is" keyword.
Line 294: Line 289:
 
var myArray : Array = new Array("v1", "v2");
 
var myArray : Array = new Array("v1", "v2");
 
</javascript>
 
</javascript>
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 refrence error.
+
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===
 
===null===
The keyword, null, is a nonexistant value. It can be used when assigning a variable, or when testing to see if a variable has a value.
+
The keyword null, is a nonexistant value. It can be assigned to a variable, or used to test whether a variable has a value.
 +
<javascript>var something = null;
 +
if(something == null)
 +
{
 +
Debug.Log("something is null!");
 +
}</javascript>
 +
You could also write the if statement like this to implicitly test for null:
 +
<javascript>if(something)
 +
{
 +
Debug.Log("something is null!");
 +
}</javascript>
 +
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===
 
===private===
Line 304: Line 310:
 
private var tmp;
 
private var tmp;
 
</javascript>
 
</javascript>
Marking a variable as private makes it so that only the instance variable owner may acsess that variable.
+
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).
On top of that, in Unity, you cannot see private variables in the editor (unless the editor is set on debug mode).
+
  
 
===protected===
 
===protected===
 +
Similar to private, but permits extending classes to access the variable or function.
 +
 
===public===
 
===public===
The public keyword allows variables to be accessed by other classes, also you will be able to edit public variables in the Unity editor. (You might also want to see private [which is the oposite of the public keyword).
+
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===
 
===return===
 +
Returns a value from a function.
 +
<javascript>function FunctionThatReturnsAString()
 +
{
 +
return "Hello";
 +
}
 +
 +
Debug.Log(FunctionThatReturnsAString()); // Result: "Hello" appears in the console log</javascript>
 +
 
===short===
 
===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
+
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===
 
===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:
 +
 +
<javascript>static var something = 10;
 +
 +
static function SomeFunction()
 +
{
 +
Debug.Log("SomeFunction called");
 +
}</javascript>
 +
 +
You can access those members like this from any other script:
 +
 +
<javascript>SomeScript.something = 20;
 +
SomeScript.SomeFunction();</javascript>
  
Lets you create a global variable.
+
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.
  
 
===super===
 
===super===
Line 356: Line 386:
 
===throw===
 
===throw===
 
The throw statement throws an exception to indicate an error has occurred  
 
The throw statement throws an exception to indicate an error has occurred  
<javascript>
 
</javascript>
 
  
 
===try===
 
===try===
Line 371: Line 399:
 
===var===
 
===var===
 
var is used to declare variables. Here are some of the formats for using var.
 
var is used to declare variables. Here are some of the formats for using var.
<javascript>
+
<javascript>var myVar;
var myVar;
+
  
 
var myVar : Type;
 
var myVar : Type;
Line 382: Line 409:
 
var myVar = new Type();
 
var myVar = new Type();
  
var myVar : Type = new Type();
+
var myVar : Type = new Type();</javascript>
</javascript>
+
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 efeciency you should not use pure dynamic typing. To disable dynamic typing in a certain file, type "#pragma strict".
+
  
 
===while===
 
===while===

Revision as of 09:00, 4 November 2010

Contents

as

TODO

boolean

The boolean keyword is used to is used to define a variable of type boolean . The boolean variables can take two values only : true or false. <javascript> var alive : boolean; function Start(){ alive = true ; if (alive==true){ Debug.Log("player is alive"); } } </javascript> The advantage of using a boolean instead of setting an integer to either 0 or 1 is that you can toggle a boolean. You can therefor 'tell' a boolean to switch its state without knowing what state it is in at the moment. Example: Switching a light on and off by pressing the same button.

break

The break keyword is used as a jump statement. It ends the execution 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). <javascript> var myByte : byte; function Start(){ myByte = 8 ; Debug.Log(myByte.ToString()); } </javascript> The sbyte is not a keyword. If someone needs the sbyte value type can access it using System.SByte <javascript> import System; var myByte : System.SByte;

function Start(){ myByte = -8 ; Debug.Log(myByte.ToString()); } </javascript>

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 <javascript> var fisrtLetter : char; fisrtLetter = 'I'; </javascript> You can use the following hack though <javascript> var firstLetter : char; function Start(){ firstLetter = "g"[0]; print (firstLetter); } </javascript>

class

The class keyword is used for defining a class (classes are an Object-Oriented feature). The class is a blueprint for Objects ie describes what properties (think them as variables) and methods (think them as functions) a new object of this class has. Lets make a woman class. The woman object will have

  • two properties : name and hair color
  • one method : talk

<javascript> 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){ Debug.Log(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); } </javascript>

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. <javascript> // 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 + " "); } } </javascript> Lets see what happens if we remove the continue statement <javascript> // 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 + " "); } } } </javascript>

default

See the switch keyword for more info and examples.

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). <javascript> var myDouble : double;

function Start(){

   myDouble = 8321.2 ;
   Debug.Log(myDouble.ToString());

} </javascript>

else

See the documentation for the if keyword.

enum

An enum (which I will refer to as enumeration) is a special value type 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, ie 0 is assigned to the first member, 2 to the second etc. <javascript> // 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 va GUI instead 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; } } </javascript>

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 <javascript>class myClass extends MonoBehaviour { //your code }</javascript>

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; <javascript> </javascript>

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. <javascript> function FunctionName() { ... }

function FunctionName(param : paramType) { ... }

(note, you can have as many parameters as you want...)

function FunctionName() : returnType { ... }

function FunctionName(param : paramType) : returnType { ... } </javascript> 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:

<javascript> var myVar : int = Return4(); //myVar would then equal 4. </javascript>

  • 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: <javascript> if (expression){

   statement1;

} else{

   statement2;

} </javascript> 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: <javascript> if (expression1){

 if (expression2){
     statement1;
     statement2;
 }

} else{

     statement3;

} </javascript>

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. <javascript> var array : Array = new Array ("v1", "v2", "v3"); for (var tmp : String in array) {

 print (tmp);

} </javascript> An alternate way of writing this (without a in statment) would be like this. <javascript> 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;

} </javascript> 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. <javascript> class _paddle { } class _paddle2 { }

function Start(){ var player1Paddle = new _paddle2(); if (player1Paddle instanceof _paddle){ print("yes it is"); } else{ print("no it is not"); } } </javascript>

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. <javascript> var myArray : Array = new Array("v1", "v2"); </javascript> 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. <javascript>var something = null; if(something == null) { Debug.Log("something is null!"); }</javascript> You could also write the if statement like this to implicitly test for null: <javascript>if(something) { Debug.Log("something is null!"); }</javascript> 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: <javascript> private var tmp; </javascript> 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. <javascript>function FunctionThatReturnsAString() { return "Hello"; }

Debug.Log(FunctionThatReturnsAString()); // Result: "Hello" appears in the console log</javascript>

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:

<javascript>static var something = 10;

static function SomeFunction() { Debug.Log("SomeFunction called"); }</javascript>

You can access those members like this from any other script:

<javascript>SomeScript.something = 20; SomeScript.SomeFunction();</javascript>

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.

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. <javascript> 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
 

} </javascript> 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. <javascript> switch(i) </javascript> 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. <javascript>

   case 4:
      // if i equals 4 then this block of code is executed
   break;

</javascript>

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

try

typeof

The typeof keyword (used like "typeof(variable)") will return a string. The string will be

  • number
  • string
  • boolean
  • object
  • function
  • undefined

var

var is used to declare variables. Here are some of the formats for using var. <javascript>var myVar;

var myVar : Type;

var myVar = value;

var myVar : Type = value;

var myVar = new Type();

var myVar : Type = new Type();</javascript> 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".

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 <javascript> while (condition) { ... } </javascript>

Personal tools
Namespaces

Variants
Actions
Navigation
Extras
Toolbox