Small snippets of UnityScript

CountChildren

Input : a transform
Output : Number of children all hierarchy levels down.
Interesting : Use of recursion.

function countChildren(tr : Transform):int
{ 
    var i : int  = 0;
    var t : Transform;
    
    for ( t in tr )
    { 
        i += countChildren(t) + 1; 
    }

    return i; 
}

How to make a custom class that exposes its fields in the inspector

//Allows you to add this script to a GO, make sure you
//name the script with the same name (e.g. in this example myDummyClass)
public class myDummyClass extends MonoBehaviour
{
    //The above instance shows in the inspector
    public var myClassInstance : myClass;
    //Allows the inspector to see inside your custom class
    public class myClass extends System.Object
    {
        public var nameField : String = "My Class Name field value";
    }
}

Properties in js (Thanks again Neil - Mike )

public class myDummyClass extends MonoBehaviour
{
    public var myClassInstance : myClass;
    
    public class myClass extends System.Object
    {
        public var nameField : String = "My Class Name field value";
        public var moneyField : int = 0;
        
         function get HasMoneyProperty():boolean
        {
            return moneyField > 0;
        }
    }
    
    function Start()
    {
        myClassInstance = new myClass();
        myClassInstance.moneyField = 10;
        Debug.Log(myClassInstance.moneyField.ToString());
        Debug.Log(myClassInstance.HasMoneyProperty.ToString());
        myClassInstance.moneyField = 0;
        Debug.Log(myClassInstance.moneyField.ToString());
        Debug.Log(myClassInstance.HasMoneyProperty.ToString());
    }
}

Regarding the previous script, wouldn’t you just do:

public class MyClass
{
    public var nameField : String = "My Class Name field value";
}

var foo : MyClass;

?

Regarding properties, I think this would work better:

public class MyClass
{
    public var nameField : String = "My Class Name field value";
    public var moneyField : int = 5;
    function get hasMoneyProperty() : boolean
    {
        return moneyField > 0;
    }
}

var foo : MyClass;

Also note my bugfix in the getter. :wink:

–Eric

Thanks Eric :slight_smile:

So I tried doing properties in Unityscript quite some time ago, failed completely, and figured it was just impossible.
Turns out you can only declare get functions inside a class.

As in, you have to explicitly have a class:

class Mine extends MonoBehaviour {
  function get property() : int { return 1; }
}

If you remove the class declaration, suddenly ‘get’ is an unexpected token (even though… I’m declaring a class by simply having the script exist).