Unity API

Using the API with a Unity Web Player or WebGL game

It is possible to access the JavaScript API from a Unity game on Kongregate using the Application.ExternalCall and Application.ExternalEval functions from within your Unity application.

Loading the API

In order to access the Javascript API from Unity, the following script tag should be included in the head tag of the same page as your application:

<script src='https://cdn1.kongregate.com/javascripts/kongregate_api.js'></script>

Depending on how your game is built and hosted, there are several different ways to load the JavaScript API for use with Unity:

  • WebGL games: The script needs to be included in your HTML. See this blog post for more details.
  • Externally hosted (iframe) Web Player games: Include the script in the head section of your HTML.
  • Web Player games uploaded to Kongregate: The script will be included automatically.

Initializing the API

Note for games using the Kongregate Mobile SDK

The SDK will automatically initialize the Javascript API for you, and you do not need to do it manually.

Once the JavaScript API is loaded, you can make calls on the global kongregateUnitySupport helper object that the script creates on your behalf.

The kongregateAPI object has a method named initAPI which takes the following parameters:

Name
Type
Description

game_object_name

String

The name of the Unity GameObject to perform the callback method on

callback_name

String

The name of the function to be called on the given object

The callback will be invoked with a single string argument which contains tokenized user information. The string contains the user id, username, and game_auth_token of the current user, separated by the vertical pipe | character.

The following is an example of how to use the kongregateUnitySupport object to load the Kongregate API and notify your Unity application when the loading is completed. You generally want to do this from a GameObject that only gets instantiated once and stays persistent during the entire life of your application.

Example: A MonoBehaviour that initializes the API, ensures only one instance will be created, and calls the OnKongregateAPILoaded function on the KongregateAPI game object when done.

public class KongregateAPIBehaviour : MonoBehaviour {
  private static KongregateAPIBehaviour instance;
  
  public void Start() {
    if(instance == null) {
    	instance = this;
    } else if(instance != this) {
    	Destroy(gameObject);
      return;
    }
    
    Object.DontDestroyOnLoad(gameObject);
    gameObject.name = "KongregateAPI";

    Application.ExternalEval(
      @"if(typeof(kongregateUnitySupport) != 'undefined'){
        kongregateUnitySupport.initAPI('KongregateAPI', 'OnKongregateAPILoaded');
      };"
    );
  }

  public void OnKongregateAPILoaded(string userInfoString) {
    OnKongregateUserInfo(userInfoString);
  }  

  public void OnKongregateUserInfo(string userInfoString) {
    var info = userInfoString.Split('|');
    var userId = System.Convert.ToInt32(info[0]);
    var username = info[1];
    var gameAuthToken = info[2];
    Debug.Log("Kongregate User Info: " + username + ", userId: " + userId);
  }
}
#pragma strict

public class KongregateAPIBehaviour extends MonoBehaviour {
	private static var instance:KongregateApiBehaviour;

	function Start () {
	  if(instance == null) {
	  	instance = this;
	  } else {
	  	Destroy(gameObject);
	    return;
	  }

	  DontDestroyOnLoad(gameObject);
	  gameObject.name = "KongregateAPI";

	  var script =
	  "if(typeof(kongregateUnitySupport) != 'undefined') { " +
	  "  kongregateUnitySupport.initAPI('KongregateAPI', 'OnKongregateAPILoaded');" +
	  "};";

	  Application.ExternalEval(script);
	}

	function OnKongregateAPILoaded(userInfoString:String) {
	  OnKongregateUserInfo(userInfoString);

	  var script =
	  "kongregate.services.addEventListener('login', function() {" +
	  "  var unityObject = kongregateUnitySupport.getUnityObject();" +
	  "  var services = kongregate.services;" +
	  "  var params=[services.getUserId(), services.getUsername()," +
	  "              services.getGameAuthToken()].join('|');" +
	  "  unityObject.SendMessage('KongregateAPI', 'OnKongregateUserInfo', params);" +
	  "});";

	  Application.ExternalEval(script);
	}

	function OnKongregateUserInfo(userInfoString:String) {
	  var info = userInfoString.Split("|"[0]);
	  var userId = parseInt(info[0]);
	  var username = info[1];
	  var gameAuthToken = info[2];
	  Debug.Log("Kongregate User Info: " + username + ", userId: " + userId);
	}
}

Note the use of the Application.ExternalEval function to call out to the kongregateUnitySupport JavaScript object if it exists. When the API completes loading, it will use Unity's SendMessage function to call the given function on the Unity game object with the name passed in. Also, make sure you do not load the API more than once - this will cause the API connection to break.

Using the API

Now that the API has been initialized, you are able to use any of the Javascript API functionality from within your Unity script by referencing the kongregate object that exists in JavaScript.

Functions which don't require a callback are relatively simple, such as submitting a statistic. (Note that you will also need to set up Statistics for your game, as described in our Statistics & High Scores documentation)

Example: Submit a statistic named "Score" with a value of 1000.

Application.ExternalCall("kongregate.stats.submit", "Score", 1000);
Application.ExternalCall("kongregate.stats.submit", "Score", 1000);

Callbacks & Asynchronous Methods

Many Kongregate API functions (such as the user sign-in event) and Kreds functionality require you to define a callback in order to function properly. In order to handle this in Unity, you must use their SendMessage method to send data back into your game.

In general you will want to use Unity's Application.ExternalEval method to create a JavaScript closure that will perform the SendMessage call when the results of the operation have been received. The SendMessage function will call the method on the named GameObject that you specify, and will pass in any additional arguments as strings.

Below is an example of how to handle the user sign-in event callback using Unity, by modifying the OnKongregateAPILoaded function from the previous example to call the OnKongregateUserInfo function when a Kongregate user signs in.

Example: Register a listener for the user sign-in event after initializing the API:

public void OnKongregateAPILoaded(string userInfoString){
  OnKongregateUserInfo(userInfoString);

  Application.ExternalEval(@"
      kongregate.services.addEventListener('login', function(){
        var unityObject = kongregateUnitySupport.getUnityObject();
        var services = kongregate.services;
        var params=[services.getUserId(), services.getUsername(), 
                    services.getGameAuthToken()].join('|');

        unityObject.SendMessage('KongregateAPI', 'OnKongregateUserInfo', params);
    });"
  );
}
function OnKongregateAPILoaded(userInfoString:String) {
  OnKongregateUserInfo(userInfoString);
  
  var script =
  "kongregate.services.addEventListener('login', function() {" +
  "  var unityObject = kongregateUnitySupport.getUnityObject();" +
  "  var services = kongregate.services;" +
  "  var params=[services.getUserId(), services.getUsername()," +
  "              services.getGameAuthToken()].join('|');" +
  "  unityObject.SendMessage('KongregateAPI', 'OnKongregateUserInfo', params);" +
  "});";
  
  Application.ExternalEval(script);
}

Example: Purchase an item, passing the result back into a GameObject via SendMessage. Note that in this example, a Unity GameObject must exist called MyGameObject with the methods OnPurchaseSuccess and OnPurchaseFailure.

Application.ExternalEval(@"
	kongregate.mtx.purchaseItems(['sword'], function(result) {
  	var unityObject = kongregateUnitySupport.getUnityObject();
    if (result.success) {
    	unityObject.SendMessage('MyGameObject', 'OnPurchaseSuccess', '');
    } else {
    	unityObject.SendMessage('MyGameObject', 'OnPurchaseFailure', '');
    }
  });
");

Notes

  • If you are using the Kongregate shell for an external iframe game, you do not need to manually load/initialize the API, and you can access the API functions through parent.kongregate
  • For externally hosted Web Player games your Unity DOM element must have an ID of unityPlayer in order for the API to function properly. If you are using a different ID, you can set kongregateAPI.unityElementId to the ID of your element.
  • For information about hosting Unity WebGL games on Kongregate, see this blog post.