Tuesday, March 05, 2013

Unity engine: Scripting

Asset > Create > Javascript

A JS file will be created in Assets view. It is like a class. It can be dragged to be added into a GameObject in Hierarchy. but the variable will be available in the Inspector view. its value can be changed there. it will NOT be taken from the default value in the script file. The variable / property name will automatically starts with Uppercase letter.


print() is use to print to console.

to access other GameObject in scene, use GameObject.Find("game object tag")
to access component in GameObject, use GetComponent("component name")

Example:

#pragma strict
// a script file is like a class
// a member variable
var i = 1;
var speed = 0.1;
// start calls once
function Start () {
// testing while loop
while(i < 10){
// it's like trace in Flash and echo/print in PHP
// prints to console.
print("hello ");
i++;
}
// instantiate a object / component by adding to the GameObject
// gameObject is built-in as this script is added to a GameObject
// declare class type of variable using ":"
var obj:MyClass = gameObject.AddComponent("MyClass");
// call a method
obj.myMethod();
}

// updates every frame
function Update () {
// rotate around z-axis by speed x time(s) taken to complete last frame
transform.Rotate(0, 0, speed * Time.deltaTime);
// transform is built-in for GameObject
transform.position.y+=0.1;

// testing if statement
if(transform.position.y > 300){
transform.position.y = 0;
}

}

NOTE: there is no %= operator. so has to do something like: number = number % 10;

creating a class: create a JS file. put the class code in. sample below:

class MyCustomClass{
var myVar = 10;
var myName = "TBY";

function MyMethod(){
myVar++;
return myVar;
}

static function MyStaticMethod(num){
return num*num;
}
}


to create an instance, sample:

print(MyCustomClass.MyStaticMethod(10));
var obj:MyCustomClass = new MyCustomClass();
print(obj.MyMethod());

No comments: