UnityScript Keywords

From Unify Community Wiki
Revision as of 20:48, 10 January 2012 by NCarter (Talk | contribs)

Jump to: navigation, search

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");
	}
}
</javascript>
 
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.
 
<syntaxhighlight lang="javascript">
 
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.
}
 
</javascript>
 
===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).
<syntaxhighlight lang="javascript">
var myByte : byte;
function Start(){
	myByte = 8 ;
	print(myByte.ToString());
}
</javascript>
The ''sbyte'' is not a keyword. If someone needs the sbyte value type can access it using 
System.SByte
<syntaxhighlight lang="javascript">
import System;
var myByte : System.SByte;
 
function Start(){
	myByte = -8 ;
	print(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
<syntaxhighlight lang="javascript">
var fisrtLetter : char;
fisrtLetter = 'I'; // does NOT work.
</javascript>
You can use the following hack, though:
<syntaxhighlight lang="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 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
<syntaxhighlight lang="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) {
		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 + ".");
}
</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. 
<syntaxhighlight lang="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
<syntaxhighlight lang="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).
<syntaxhighlight lang="javascript">
var myDouble : double;
 
function Start(){
    myDouble = 8321.2 ;
    print(myDouble.ToString());
}
</javascript>
===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).
<syntaxhighlight lang="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 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;
	}
}
</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 
<syntaxhighlight lang="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; 
<syntaxhighlight lang="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.
<syntaxhighlight lang="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:
<syntaxhighlight lang="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:
<syntaxhighlight lang="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:
<syntaxhighlight lang="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.
<syntaxhighlight lang="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.
<syntaxhighlight lang="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.
<syntaxhighlight lang="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.
<syntaxhighlight lang="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.
<syntaxhighlight lang="javascript">var something = null;
if(something == null)
{
	print("something is null!");
}</javascript>
You could also write the if statement like this to implicitly test for null:
<syntaxhighlight lang="javascript">if(something)
{
	print("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:
<syntaxhighlight lang="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.
<syntaxhighlight lang="javascript">function FunctionThatReturnsAString()
{
	return "Hello";
}
 
print(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:
 
<syntaxhighlight lang="javascript">static var something = 10;
 
static function SomeFunction()
{
	print("SomeFunction called");
}</javascript>
 
You can access those members like this from any other script:
 
<syntaxhighlight lang="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.
<syntaxhighlight lang="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.
<syntaxhighlight lang="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.
<syntaxhighlight lang="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.
<syntaxhighlight lang="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
<syntaxhighlight lang="javascript">
while (condition) { ... } 
</javascript>
Personal tools
Namespaces

Variants
Actions
Navigation
Extras
Toolbox