Using Plugins with Java Script
The plugin API is available with the C# only.
However, there is a trick how we can use plugin API from JS scripts.
For example, we need to connect to the Google Play if a player has not connected yet. Let's create CSharpAPIHelper.cs script which will work with the plugin API.
public class CSharpAPIHelper : MonoBehaviour {
public void ConnectToPlaySertivce() {
//listen for GooglePlayConnection events
GooglePlayConnection.instance.addEventListener (GooglePlayConnection.PLAYER_CONNECTED, OnPlayerConnected);
GooglePlayConnection.instance.addEventListener (GooglePlayConnection.PLAYER_DISCONNECTED, OnPlayerDisconnected);
if(GooglePlayConnection.state == GPConnectionState.STATE_CONNECTED) {
//checking if player already connected
OnPlayerConnected ();
} else {
Debug.Log("Connecting....");
GooglePlayConnection.instance.connect();
}
}
}
Now let's create JSUseExample.js script and attach both scripts to the same GameObject.
This will make us be able to call the function of our CSharpAPIHelper.cs from the JSUseExample.js script. We will use Send Message for this. Let's create Connect button which will call ConnectToPlaySertivce method from the C# script.
#pragma strict
function OnGUI () {
if (GUI.Button(new Rect(10, 70, 200, 70), "Connect")) {
//calling ConnectToPlaySertivce function of CSharpAPIHelper
//CSharpAPIHelper should be attached to the same gameobject
gameObject.SendMessage ("ConnectToPlaySertivce");
}
}
In the same way we can send events from the C# script to the JS script.
CSharpAPIHelper.cs
private void OnPlayerConnected() {
//Sedning Event back to JS
gameObject.SendMessage("PlayerConnectd");
}
private void OnPlayerDisconnected() {
//Sedning Event back to JS
gameObject.SendMessage("PlayerDisconected");
}
JSUseExample.js
function PlayerConnectd() {
Debug.Log("Player Connected Event received");
}
function PlayerDisconected() {
Debug.Log("Player Disconected Event received");
}