ruk·si

⬜️ UnityScript
Guide

Updated at 2013-01-30 23:43

UnityScript is a language that is modelled after JavaScript, but is totally different language. UnityScript is used with Unity.

Enforce strict typing.

#pragma strict

Do not allow implicitly declared variables when using #pragma strict.

// bad
#pragma strict
#pragma implicit
foo = 5;

// good
#pragma strict
var foo = 5;

Allow casting from a super type to a sub type when using #pragma strict.

// bad, Instantiate() returns Object, not GameObject
#pragma strict
var go : GameObject;
var clone : GameObject = Instantiate(go);

// bad, implicit castas are not good practice
#pragma strict
#pragma downcast
var go : GameObject;
var clone : GameObject = Instantiate(go);

// good
#pragma strict
var go : GameObject;
var clone : GameObject = Instantiate(go) as GameObject;

Prefer using enum rather than obscure string values.

enum WeaponType { pistol, rifle, launcher}
var type : WeaponType = WeaponType.pistol;

Each UnityScript file implements one class by default.

// Foo.js
var x : int;
function doEet() {}

// Is same as.

// Foo.js
class Foo extends MonoBehaviour {
    var x : int;
    function doEet() {}
}

// You can define utility classes in same file though.

// Static functions and variables in a class are
// class functions and variables.

Basic inheritance is done with extends.

// PrintingFoo.js
class PrintingFoo extends Foo {
    function doEet() {
        print( foo );
    }
}

Virtual functions will be used from the child class.

// Foo.js
class Foo {
     virtual function DoSomething () {
         Debug.Log("from base class");
     }
}

// SubFoo.js
class SubFoo extends Foo {
    virtual function DoSomething() {
        Debug.Log("from sub class");
    }
}

// Somewhere else...
var foo : Foo = new SubFoo();
foo.DoSomething();
// Prints 'from sub class'.

Calling parent class is done with super.

// SubFoo.js
class SubFoo extends Foo {
     virtual function DoSomething() {
        super.DoSomething();
        Debug.Log("from sub class");
     }
}

// Elsewhere
var foo : Foo = new SubFoo();
foo.DoSomething();
// Prints "from base class" and "from sub class"

Prefer composition over inheritance.

// Foo.js
var bar : Bar;

function Start() {
    bar = gameObject.GetComponent(Bar);
}

function doEet() {
    // Do my own thing
    if ( bar ) {
        bar.doEet();
    }
}

// Bar.js
function doEet() {
    // Do something special.
}

String splitting.

var qualifiedName : String = "System.Integer myInt";
var name = qualifiedName.Split(" "[0]);
// myInt

String replace.

// Replace all the underscores with spaces.
var s : String = "Whatever_it_may_be";
s = s.Replace("_"[0], " "[0]);

Arrays

var a = new Array();
a.Push(4);
// This works

public var friendsOfCarlotta : Transform[];

Debugging

Debug.Log("insert message here");

Debug.LogWarning

Debug.LogError

// Pause the execution.
Debug.Break();