Using the API with a Unity WebGL game

Unity WebGL games should use the Kongregate Javascript API. This will require you to write a javascript plugin (jsLibs) to access the javascript api from Unity C#. Additionally, Unity games can use the Kongregate WebGL Template which includes a Unity Preloader that loads the Javascript API.

Download the WebGL Template

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 (if you are using our Unity Preloader this is already included for you):

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

Set Your UnityInstance

If you are using our provided WebGL Template, it handles this step for you.

Otherwise, you can make use of Unity's createUnityInstance to set the window.unityInstance to your Unity instance. Do not skip this step or you will not be able to access the Kongregate API!

createUnityInstance(canvas, config, (progress) => {
  //Update any loading information here
}).then((unityInstance) => {
  window.unityInstance = unityInstance;
  //Hide loading information here
}).catch((message) => {
  //Handle any loading errors here
});

Initializing the API

Once the JavaScript API is loaded, you can make calls to the kongregate api using unity bindings.

Example: A MonoBehaviour that initializes the API, ensures only one instance will be created, and calls the LoadKongregateJavascriptAPI() extern function that is bound to the same named function in the jsLib file (see javascript tab). When the javascript api is loaded, the OnKongregateAPILoaded callback will be invoked and you can begin using the api. The javascript should be packaged in a file ending with extension "jsLib" and placed in the Plugins folder in your unity project.

public class KongregateAPIBehaviour : MonoBehaviour {
  private static KongregateAPIBehaviour instance;
  
  public delegate void KongregateCallbackDelegate(string result);
  
 [DllImport("__Internal")]
  private static extern void LoadKongregateJavascriptAPI();
  
 [DllImport("__Internal")]
  private static extern void StatsSubmitStat(string name, double value);
  
 [DllImport("__Internal")]
  private static extern void PurchaseItems(string item);
  
 [DllImport("__Internal")]
  private static extern void CallbackExampleFunction(KongregateCallbackDelegate callback);

  public void Start() {
    if(instance == null) {
    	instance = this;
    } else if(instance != this) {
    	Destroy(gameObject);
      return;
    }
    
    LoadKongregateJavascriptAPI();
  }

  private void OnKongregateAPILoaded()
  {
        Debug.Log("--------The kongregate api is ready------");
        StatsSubmitStat("Score", 1000);
        PurchaseItems("test_item");
    		CallbackTestFunction(OnCallbackResut);
  }
  
  void OnCallbackResut(string result)
  {
      Debug.Log("Callback Result: " + result);
  }
 
  void OnPurchaseProductResult(string result)
  {
      Debug.Log("OnPurchaseProductResult: " + result);
  }

}
mergeInto(LibraryManager.library, {

  LoadKongregateJavascriptAPI: function() {
    if(typeof(kongregateUnitySupport) != 'undefined'){
      kongregateUnitySupport.initAPI('KongregateAPIBehaviour', 'OnKongregateAPILoaded');
    };
  },

  StatsSubmitStat: function(name, value) {
    kongregate.stats.submit(UTF8ToString(name), value);
  },
  
  PurchaseItems: function (str) {
    var stringArray = [];
    stringArray.push(UTF8ToString(str));
    kongregate.mtx.purchaseItems(stringArray, function(result){{
          var status = result.success ? 'SUCCESS' : 'FAIL';
          // Fire the callback in the Unity code
          kongregateUnitySupport.getUnityObject().SendMessage('KongregateAPIBehaviour', 'OnPurchaseProductResult', status);
        }});
  },

  CallbackExampleFunction: function(callback) {
    callback();
  }

});

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 via the bindings you have created with the jsLib file.

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.

StatsSubmitStat("Score", 100);
kongregate.stats.submit("Score", 1000);

Callbacks & Asynchronous Methods

Many Kongregate API functions (such as the user sign-in event) and Kreds functionality require a callback in order to function properly. In order to handle this in Unity, you can create a delegate that can handle callbacks.

Below is an example snippet of using a delegate to invoke a callback in unity (the entire class example is posted above).

Example: Invoke a javascript function from unity and passing a callback function.

 public delegate void KongregateCallbackDelegate(string result);

[DllImport("__Internal")]
 private static extern void CallbackExampleFunction(KongregateCallbackDelegate callback);

 CallbackTestFunction(OnCallbackResut);

 void OnCallbackResut(string result)
 {
    Debug.Log("Callback Result: " + result);
 }
  CallbackExampleFunction: function(callback) {
    callback();
  }

Example: Purchase an item, passing the result back into a GameObject via SendMessage.

[DllImport("__Internal")]
private static extern void PurchaseItems(string item);

PurchaseItems("test_item");

  PurchaseItems: function (str) {
    var stringArray = [];
    stringArray.push(UTF8ToString(str));
    kongregate.mtx.purchaseItems(stringArray, function(result){{
          var status = result.success ? 'SUCCESS' : 'FAIL';
          // Fire the callback in the Unity code
          kongregateUnitySupport.getUnityObject().SendMessage('KongregateAPIBehaviour', 'OnPurchaseProductResult', status);
        }});
  }