{"_id":"56acd698d21f1b0d00fd2f65","project":"56abbf55f25f160d00e17f4e","user":"56abbec30b9e0b0d00616274","category":{"_id":"56abca6bf9757e0d007c6650","pages":["56abcb4a678b58170031ec27","56accf7513ac890d001c3c76","56acd12a693f0a0d0085f099","56acd43d0ab3c00d00ce332d","56acd698d21f1b0d00fd2f65"],"project":"56abbf55f25f160d00e17f4e","__v":5,"version":"56abbf55f25f160d00e17f51","sync":{"url":"","isSync":false},"reference":false,"createdAt":"2016-01-29T20:24:11.577Z","from_sync":false,"order":1,"slug":"api-overview","title":"API Languages"},"parentDoc":null,"__v":18,"version":{"_id":"56abbf55f25f160d00e17f51","project":"56abbf55f25f160d00e17f4e","__v":12,"createdAt":"2016-01-29T19:36:53.665Z","releaseDate":"2016-01-29T19:36:53.665Z","categories":["56abbf56f25f160d00e17f52","56abca6bf9757e0d007c6650","56acddfa0ab3c00d00ce3332","56af65da9d32e30d0006d30f","56af66cab34d210d003d9ad0","56af6afcd21e9c0d00b628d1","56af6d6ecc4cbd0d00ce2c88","5705b12221cfed0e00e8c580","570a5676ade45d0e00c1ad33","570d7d25d1e4b82000d9e385","570eac3c3160d10e0041df0e","575709000fd6a3200010dded"],"is_deprecated":false,"is_hidden":false,"is_beta":false,"is_stable":true,"codename":"","version_clean":"1.0.0","version":"1.0"},"updates":[],"next":{"pages":[],"description":""},"createdAt":"2016-01-30T15:28:24.566Z","link_external":false,"link_url":"","githubsync":"","sync_unique":"","hidden":false,"api":{"results":{"codes":[]},"settings":"","auth":"required","params":[],"url":""},"isReference":false,"order":4,"body":"## Using the API with a Unity Web Player or WebGL game\n\nIt is possible to access the JavaScript API from a Unity game on Kongregate using the [Application.ExternalCall](http://docs.unity3d.com/ScriptReference/Application.ExternalCall.html) and [Application.ExternalEval](http://docs.unity3d.com/ScriptReference/Application.ExternalEval.html) functions from within your Unity application.\n\n### Loading the API\n\nIn order to access the [Javascript API](doc:javascript-api) from Unity, the following script tag should be included in the head tag of the same page as your application:\n[block:code]\n{\n \"codes\": [\n {\n \"code\": \"<script src='https://cdn1.kongregate.com/javascripts/kongregate_api.js'></script>\",\n \"language\": \"html\"\n }\n ]\n}\n[/block]\nDepending on how your game is built and hosted, there are several different ways to load the JavaScript API for use with Unity:\n\n* **WebGL games:** The script needs to be included in your HTML. See [this blog post](http://developers.kongregate.com/blog/unity-webgl) for more details.\n* **Externally hosted (iframe) Web Player games:** Include the script in the head section of your HTML.\n* **Web Player games uploaded to Kongregate:** The script will be included automatically.\n\n### Initializing the API\n[block:callout]\n{\n \"type\": \"info\",\n \"title\": \"Note for games using the Kongregate Mobile SDK\",\n \"body\": \"The SDK will automatically initialize the Javascript API for you, and you do not need to do it manually.\"\n}\n[/block]\nOnce the JavaScript API is loaded, you can make calls on the global `kongregateUnitySupport` helper object that the script creates on your behalf.\n\nThe `kongregateAPI` object has a method named `initAPI` which takes the following parameters:\n[block:parameters]\n{\n \"data\": {\n \"h-0\": \"Name\",\n \"h-1\": \"Type\",\n \"h-2\": \"Description\",\n \"0-0\": \"`game_object_name`\",\n \"0-1\": \"String\",\n \"0-2\": \"The name of the Unity `GameObject` to perform the callback method on\",\n \"1-0\": \"`callback_name`\",\n \"1-1\": \"String\",\n \"1-2\": \"The name of the function to be called on the given object\"\n },\n \"cols\": 3,\n \"rows\": 2\n}\n[/block]\nThe 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.\n\nThe 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.\n\n**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.\n[block:code]\n{\n \"codes\": [\n {\n \"code\": \"public class KongregateAPIBehaviour : MonoBehaviour {\\n private static KongregateAPIBehaviour instance;\\n \\n public void Start() {\\n if(instance == null) {\\n \\tinstance = this;\\n } else if(instance != this) {\\n \\tDestroy(gameObject);\\n return;\\n }\\n \\n Object.DontDestroyOnLoad(gameObject);\\n gameObject.name = \\\"KongregateAPI\\\";\\n\\n Application.ExternalEval(\\n :::at:::\\\"if(typeof(kongregateUnitySupport) != 'undefined'){\\n kongregateUnitySupport.initAPI('KongregateAPI', 'OnKongregateAPILoaded');\\n };\\\"\\n );\\n }\\n\\n public void OnKongregateAPILoaded(string userInfoString) {\\n OnKongregateUserInfo(userInfoString);\\n } \\n\\n public void OnKongregateUserInfo(string userInfoString) {\\n var info = userInfoString.Split('|');\\n var userId = System.Convert.ToInt32(info[0]);\\n var username = info[1];\\n var gameAuthToken = info[2];\\n Debug.Log(\\\"Kongregate User Info: \\\" + username + \\\", userId: \\\" + userId);\\n }\\n}\",\n \"language\": \"csharp\"\n },\n {\n \"code\": \"#pragma strict\\n\\npublic class KongregateAPIBehaviour extends MonoBehaviour {\\n\\tprivate static var instance:KongregateApiBehaviour;\\n\\n\\tfunction Start () {\\n\\t if(instance == null) {\\n\\t \\tinstance = this;\\n\\t } else {\\n\\t \\tDestroy(gameObject);\\n\\t return;\\n\\t }\\n\\n\\t DontDestroyOnLoad(gameObject);\\n\\t gameObject.name = \\\"KongregateAPI\\\";\\n\\n\\t var script =\\n\\t \\\"if(typeof(kongregateUnitySupport) != 'undefined') { \\\" +\\n\\t \\\" kongregateUnitySupport.initAPI('KongregateAPI', 'OnKongregateAPILoaded');\\\" +\\n\\t \\\"};\\\";\\n\\n\\t Application.ExternalEval(script);\\n\\t}\\n\\n\\tfunction OnKongregateAPILoaded(userInfoString:String) {\\n\\t OnKongregateUserInfo(userInfoString);\\n\\n\\t var script =\\n\\t \\\"kongregate.services.addEventListener('login', function() {\\\" +\\n\\t \\\" var unityObject = kongregateUnitySupport.getUnityObject();\\\" +\\n\\t \\\" var services = kongregate.services;\\\" +\\n\\t \\\" var params=[services.getUserId(), services.getUsername(),\\\" +\\n\\t \\\" services.getGameAuthToken()].join('|');\\\" +\\n\\t \\\" unityObject.SendMessage('KongregateAPI', 'OnKongregateUserInfo', params);\\\" +\\n\\t \\\"});\\\";\\n\\n\\t Application.ExternalEval(script);\\n\\t}\\n\\n\\tfunction OnKongregateUserInfo(userInfoString:String) {\\n\\t var info = userInfoString.Split(\\\"|\\\"[0]);\\n\\t var userId = parseInt(info[0]);\\n\\t var username = info[1];\\n\\t var gameAuthToken = info[2];\\n\\t Debug.Log(\\\"Kongregate User Info: \\\" + username + \\\", userId: \\\" + userId);\\n\\t}\\n}\\n\",\n \"language\": \"javascript\"\n }\n ]\n}\n[/block]\nNote 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](https://docs.unity3d.com/ScriptReference/GameObject.SendMessage.html) 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.\n\n### Using the API\n\nNow that the API has been initialized, you are able to use any of the [Javascript API](doc:javascript-api) functionality from within your Unity script by referencing the `kongregate` object that exists in JavaScript. \n\nFunctions 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](doc:concepts-statistics) documentation)\n\n**Example:** Submit a statistic named \"Score\" with a value of 1000.\n[block:code]\n{\n \"codes\": [\n {\n \"code\": \"Application.ExternalCall(\\\"kongregate.stats.submit\\\", \\\"Score\\\", 1000);\",\n \"language\": \"csharp\"\n },\n {\n \"code\": \"Application.ExternalCall(\\\"kongregate.stats.submit\\\", \\\"Score\\\", 1000);\",\n \"language\": \"javascript\"\n }\n ]\n}\n[/block]\n### Callbacks & Asynchronous Methods\n\nMany Kongregate API functions (such as the [user sign-in event](doc:concepts-handling-guests)) 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.\n\nIn 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.\n\nBelow 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.\n\n**Example:** Register a listener for the user sign-in event after initializing the API:\n[block:code]\n{\n \"codes\": [\n {\n \"code\": \"public void OnKongregateAPILoaded(string userInfoString){\\n OnKongregateUserInfo(userInfoString);\\n\\n Application.ExternalEval(@\\\"\\n kongregate.services.addEventListener('login', function(){\\n var unityObject = kongregateUnitySupport.getUnityObject();\\n var services = kongregate.services;\\n var params=[services.getUserId(), services.getUsername(), \\n services.getGameAuthToken()].join('|');\\n\\n unityObject.SendMessage('KongregateAPI', 'OnKongregateUserInfo', params);\\n });\\\"\\n );\\n}\",\n \"language\": \"csharp\"\n },\n {\n \"code\": \"function OnKongregateAPILoaded(userInfoString:String) {\\n OnKongregateUserInfo(userInfoString);\\n \\n var script =\\n \\\"kongregate.services.addEventListener('login', function() {\\\" +\\n \\\" var unityObject = kongregateUnitySupport.getUnityObject();\\\" +\\n \\\" var services = kongregate.services;\\\" +\\n \\\" var params=[services.getUserId(), services.getUsername(),\\\" +\\n \\\" services.getGameAuthToken()].join('|');\\\" +\\n \\\" unityObject.SendMessage('KongregateAPI', 'OnKongregateUserInfo', params);\\\" +\\n \\\"});\\\";\\n \\n Application.ExternalEval(script);\\n}\",\n \"language\": \"javascript\"\n }\n ]\n}\n[/block]\n**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`.\n[block:code]\n{\n \"codes\": [\n {\n \"code\": \"Application.ExternalEval(@\\\"\\n\\tkongregate.mtx.purchaseItems(['sword'], function(result) {\\n \\tvar unityObject = kongregateUnitySupport.getUnityObject();\\n if (result.success) {\\n \\tunityObject.SendMessage('MyGameObject', 'OnPurchaseSuccess', '');\\n } else {\\n \\tunityObject.SendMessage('MyGameObject', 'OnPurchaseFailure', '');\\n }\\n });\\n\\\");\",\n \"language\": \"csharp\"\n }\n ]\n}\n[/block]\n### Notes\n\n* 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`\n* 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.\n* For information about hosting Unity WebGL games on Kongregate, see [this blog post.](http://developers.kongregate.com/blog/unity-webgl)","excerpt":"","slug":"unity-api","type":"basic","title":"Unity API"}

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](http://docs.unity3d.com/ScriptReference/Application.ExternalCall.html) and [Application.ExternalEval](http://docs.unity3d.com/ScriptReference/Application.ExternalEval.html) functions from within your Unity application.
### Loading the API
In order to access the [Javascript API](doc:javascript-api) from Unity, the following script tag should be included in the head tag of the same page as your application:
[block:code]
{
"codes": [
{
"code": "<script src='https://cdn1.kongregate.com/javascripts/kongregate_api.js'></script>",
"language": "html"
}
]
}
[/block]
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](http://developers.kongregate.com/blog/unity-webgl) 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
[block:callout]
{
"type": "info",
"title": "Note for games using the Kongregate Mobile SDK",
"body": "The SDK will automatically initialize the Javascript API for you, and you do not need to do it manually."
}
[/block]
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:
[block:parameters]
{
"data": {
"h-0": "Name",
"h-1": "Type",
"h-2": "Description",
"0-0": "`game_object_name`",
"0-1": "String",
"0-2": "The name of the Unity `GameObject` to perform the callback method on",
"1-0": "`callback_name`",
"1-1": "String",
"1-2": "The name of the function to be called on the given object"
},
"cols": 3,
"rows": 2
}
[/block]
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.
[block:code]
{
"codes": [
{
"code": "public class KongregateAPIBehaviour : MonoBehaviour {\n private static KongregateAPIBehaviour instance;\n \n public void Start() {\n if(instance == null) {\n \tinstance = this;\n } else if(instance != this) {\n \tDestroy(gameObject);\n return;\n }\n \n Object.DontDestroyOnLoad(gameObject);\n gameObject.name = \"KongregateAPI\";\n\n Application.ExternalEval(\n @\"if(typeof(kongregateUnitySupport) != 'undefined'){\n kongregateUnitySupport.initAPI('KongregateAPI', 'OnKongregateAPILoaded');\n };\"\n );\n }\n\n public void OnKongregateAPILoaded(string userInfoString) {\n OnKongregateUserInfo(userInfoString);\n } \n\n public void OnKongregateUserInfo(string userInfoString) {\n var info = userInfoString.Split('|');\n var userId = System.Convert.ToInt32(info[0]);\n var username = info[1];\n var gameAuthToken = info[2];\n Debug.Log(\"Kongregate User Info: \" + username + \", userId: \" + userId);\n }\n}",
"language": "csharp"
},
{
"code": "#pragma strict\n\npublic class KongregateAPIBehaviour extends MonoBehaviour {\n\tprivate static var instance:KongregateApiBehaviour;\n\n\tfunction Start () {\n\t if(instance == null) {\n\t \tinstance = this;\n\t } else {\n\t \tDestroy(gameObject);\n\t return;\n\t }\n\n\t DontDestroyOnLoad(gameObject);\n\t gameObject.name = \"KongregateAPI\";\n\n\t var script =\n\t \"if(typeof(kongregateUnitySupport) != 'undefined') { \" +\n\t \" kongregateUnitySupport.initAPI('KongregateAPI', 'OnKongregateAPILoaded');\" +\n\t \"};\";\n\n\t Application.ExternalEval(script);\n\t}\n\n\tfunction OnKongregateAPILoaded(userInfoString:String) {\n\t OnKongregateUserInfo(userInfoString);\n\n\t var script =\n\t \"kongregate.services.addEventListener('login', function() {\" +\n\t \" var unityObject = kongregateUnitySupport.getUnityObject();\" +\n\t \" var services = kongregate.services;\" +\n\t \" var params=[services.getUserId(), services.getUsername(),\" +\n\t \" services.getGameAuthToken()].join('|');\" +\n\t \" unityObject.SendMessage('KongregateAPI', 'OnKongregateUserInfo', params);\" +\n\t \"});\";\n\n\t Application.ExternalEval(script);\n\t}\n\n\tfunction OnKongregateUserInfo(userInfoString:String) {\n\t var info = userInfoString.Split(\"|\"[0]);\n\t var userId = parseInt(info[0]);\n\t var username = info[1];\n\t var gameAuthToken = info[2];\n\t Debug.Log(\"Kongregate User Info: \" + username + \", userId: \" + userId);\n\t}\n}\n",
"language": "javascript"
}
]
}
[/block]
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](https://docs.unity3d.com/ScriptReference/GameObject.SendMessage.html) 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](doc: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](doc:concepts-statistics) documentation)
**Example:** Submit a statistic named "Score" with a value of 1000.
[block:code]
{
"codes": [
{
"code": "Application.ExternalCall(\"kongregate.stats.submit\", \"Score\", 1000);",
"language": "csharp"
},
{
"code": "Application.ExternalCall(\"kongregate.stats.submit\", \"Score\", 1000);",
"language": "javascript"
}
]
}
[/block]
### Callbacks & Asynchronous Methods
Many Kongregate API functions (such as the [user sign-in event](doc:concepts-handling-guests)) 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:
[block:code]
{
"codes": [
{
"code": "public void OnKongregateAPILoaded(string userInfoString){\n OnKongregateUserInfo(userInfoString);\n\n Application.ExternalEval(@\"\n kongregate.services.addEventListener('login', function(){\n var unityObject = kongregateUnitySupport.getUnityObject();\n var services = kongregate.services;\n var params=[services.getUserId(), services.getUsername(), \n services.getGameAuthToken()].join('|');\n\n unityObject.SendMessage('KongregateAPI', 'OnKongregateUserInfo', params);\n });\"\n );\n}",
"language": "csharp"
},
{
"code": "function OnKongregateAPILoaded(userInfoString:String) {\n OnKongregateUserInfo(userInfoString);\n \n var script =\n \"kongregate.services.addEventListener('login', function() {\" +\n \" var unityObject = kongregateUnitySupport.getUnityObject();\" +\n \" var services = kongregate.services;\" +\n \" var params=[services.getUserId(), services.getUsername(),\" +\n \" services.getGameAuthToken()].join('|');\" +\n \" unityObject.SendMessage('KongregateAPI', 'OnKongregateUserInfo', params);\" +\n \"});\";\n \n Application.ExternalEval(script);\n}",
"language": "javascript"
}
]
}
[/block]
**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`.
[block:code]
{
"codes": [
{
"code": "Application.ExternalEval(@\"\n\tkongregate.mtx.purchaseItems(['sword'], function(result) {\n \tvar unityObject = kongregateUnitySupport.getUnityObject();\n if (result.success) {\n \tunityObject.SendMessage('MyGameObject', 'OnPurchaseSuccess', '');\n } else {\n \tunityObject.SendMessage('MyGameObject', 'OnPurchaseFailure', '');\n }\n });\n\");",
"language": "csharp"
}
]
}
[/block]
### 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.](http://developers.kongregate.com/blog/unity-webgl)