Coherent UI for Unity3D  2.5.3
A modern user interface library for games
 All Classes Namespaces Functions Variables Enumerations Enumerator Properties Events Pages
Unity Script Binding

Sample Unity Script Binding

This is a sample script that binds a function in Unity engine that is to be called from JavaScript. The interface used for the binding is exactly the same as in C#.

The first example shows how a manual binding is done.

#pragma strict
import Coherent.UI.Binding;
var m_View : CoherentUIView ;
// Use this for initialization
function Start ()
{
m_View = GetComponent(typeof(CoherentUIView)) as CoherentUIView;
//Listen for the ReadyForBindings event
m_View.Listener.ReadyForBindings += HandleReadyForBindings;
}
function HandleReadyForBindings ( frameId:int,
path:String,
isMainFrame : boolean)
{
if (isMainFrame)
{
/* Bind FunctionInUnity so that JavaScript can call it */
Debug.Log("Ready for bindings..");
m_View.View.BindCall("CallFunctionInUnity", this.FunctionInUnity);
}
}
function FunctionInUnity()
{
Debug.Log("SUCCESS! This function is called from Javascript!");
}

Here is another sample - the same code used to the the binding in BindingSample, but in UnityScript and using the automatic binding feature of CoherentUI.

#pragma strict
import Coherent.UI.Binding; // to use View.TriggerEvent with extra arguments
public class GameOptions {
var Backend : String;
var Width : String;
var Height : String;
var NetPort : String;
function GameOptions(){
this.Backend = "Unity3D";
this.Width = "1024";
this.Height = "768";
this.NetPort = "17777";
}
function GameOptions(backend : String,
width : String,
height : String,
netPort : String) {
this.Backend = backend;
this.Width = width;
this.Height = height;
this.NetPort = netPort;
}
}
private var m_View : CoherentUIView;
private var m_GameOptions;
function Start () {
m_View = GetComponent(typeof(CoherentUIView)) as CoherentUIView;
m_GameOptions = new GameOptions("Unity3D", "1024", "768", "17777");
}
@Coherent.UI.CoherentMethod ("ApplyOptions", false)
function ApplyOptions(options : GameOptions)
{
m_View.View.TriggerEvent("gameConsole:Trace", options);
}
@Coherent.UI.CoherentMethod("GetLatency")
function GetNetworkLatency()
{
// not actual latency :)
return 100;
}
@Coherent.UI.CoherentMethod("GetGameTime")
function GetGameTime()
{
// not actual time :)
return 20;
}
@Coherent.UI.CoherentMethod("ViewReady", true)
function ViewReady()
{
// show the options
m_View.View.TriggerEvent("OpenOptions", m_GameOptions);
}