-
Notifications
You must be signed in to change notification settings - Fork 74
Binding JavaScript functions to C# callbacks
Rycul edited this page Jul 17, 2013
·
4 revisions
This page assumes that you have succesfully set up an AwesomiumUnityWebTexture to render a webpage within Unity.
The following C# code can be copied and used as a Component on a GameObject that also has an AwesomiumUnityWebTexture component.
[RequireComponent(typeof(AwesomiumUnityWebTexture))]
public class JavaScriptCallbackExample : MonoBehaviour
{
private AwesomiumUnityWebTexture m_WebTexture = null;
// Use this for initialization
void Start ()
{
// Obtain the web texture component.
m_WebTexture = GetComponent<AwesomiumUnityWebTexture>();
// Check to make sure we have an instance.
if (m_WebTexture == null)
{
DestroyImmediate(this);
}
// Bind a C# function to a javascript function.
m_WebTexture.WebView.BindJavaScriptCallback("MyFunction", this.Callback_MyFunction); // Can be called from the HTML page by using: Unity.PlayGame();
}
void Callback_MyFunction()
{
Debug.Log("I was called from JavaScript!");
}
}
The following JavaScript code can be called from anywhere on your HTML page.
Unity.MyFunction();
Note: If the Unity object does not exist (yet), the function will fail and possibly crash the Awesomium process. It is advisable to check whether the Unity object exists before calling any function on it. This check is performed as follows:
if (typeof window["Unity"] !== "undefined")
{
// Unity object exists!
}