Unity
Unity
The Unity package com.zokogames.sdk (Unity 2021.3 or newer, WebGL builds) wraps the JavaScript SDK in one static class, ZokoGames.ZokoSDK. Every method has a callback form and an ...Async form returning a Task.
Install#
- Open Window > Package Manager > Add package from disk and choose the package's
package.json(or add the folder to your project'sPackages/manifest.json). - Run ZokoGames > Install WebGL Template. It copies the template into
Assets/WebGLTemplates/ZokoGamesand selects it in Player Settings. The template loads the SDK script before the Unity loader. - Optional: ZokoGames > Create Simulator Settings creates
Assets/Resources/ZokoSDKSettingsfor the editor simulator.
Build for WebGL, upload the build folder in the developer console and preview it.
Initialise#
using UnityEngine;
using ZokoGames;
public class Boot : MonoBehaviour
{
void Start()
{
ZokoSDK.Init(error =>
{
if (error != null) Debug.LogWarning("ZokoGames init failed: " + error);
Debug.Log("Environment: " + ZokoSDK.Environment); // "local", "zokogames" or "disabled"
ZokoSDK.Game.SettingsChanged += s => AudioListener.pause = s.MuteAudio;
StartGame();
});
}
}| Member | Meaning |
|---|---|
ZokoSDK.IsInitialized |
Init completed. |
ZokoSDK.IsAvailable |
Initialised and not disabled. |
ZokoSDK.Environment |
"local", "zokogames" or "disabled". |
ZokoSDK.IsQaTool |
Running in the QA tool. |
ZokoSDK.IsSimulated |
The editor or native simulator is answering. |
Mapping#
| Module | JavaScript | Unity |
|---|---|---|
| Ad | ad.requestAd(type, cbs) |
Ad.RequestAd(ZokoAdType.Midgame, adStarted, adFinished, adError) or Ad.RequestAdAsync(type) |
| Ad | ad.hasAdblock() |
Ad.HasAdblock(cb) / Ad.HasAdblockAsync() |
| Banner | banner.requestBanner({id,width,height}) |
Banner.RequestBanner(id, w, h, screenRect, done) or the ZokoBanner component |
| Banner | banner.requestResponsiveBanner(id) |
Banner.RequestResponsiveBanner(id, screenRect, done) |
| Banner | clearBanner, clearAllBanners |
Banner.ClearBanner(id), Banner.ClearAllBanners() |
| Game | game.gameplayStart/Stop |
Game.GameplayStart(), Game.GameplayStop() |
| Game | loadingStart/Stop, happytime |
Game.LoadingStart(), Game.LoadingStop(), Game.Happytime() |
| Game | reportGameCompletedPercentage |
Game.ReportGameCompletedPercentage(float) |
| Game | setGameContext, clearGameContext |
Game.SetGameContext(IDictionary<string, object>), Game.ClearGameContext() |
| Game | settings, listener |
Game.Settings, event Game.SettingsChanged |
| Game | rooms and invites | Game.UpdateRoom(ZokoRoomUpdate), Game.LeftRoom(), Game.InviteLink(params, cb), Game.InviteParams, Game.GetInviteParam(key), Game.IsInstantMultiplayer, event Game.JoinRoom |
| User | getUser |
User.GetUser(cb) / User.GetUserAsync() |
| User | listFriends({page,size}) |
User.ListFriends(page, size, cb) |
| User | getUserToken |
User.GetUserToken(cb, ZokoSigningKeyType) |
| User | showAuthPrompt, listener |
User.ShowAuthPrompt(cb), event User.AuthChanged |
| User | showAccountLinkPrompt |
User.ShowAccountLinkPrompt(cb) (calls back true for yes) |
| User | systemInfo, isUserAccountAvailable |
User.SystemInfo, User.IsUserAccountAvailable |
| User | submitScore |
User.SubmitScore(encryptedScore, score, done) |
| Data | getItem ... clear |
Data.GetItem/SetItem/RemoveItem/Clear, plus GetString/SetString/GetInt/SetInt/GetFloat/SetFloat/HasKey/DeleteKey/DeleteAll |
| Analytics | trackOrder(provider, order) |
Analytics.TrackOrder(provider, order, done) |
Errors arrive as ZokoError (Code, Message, ContainerId). The ...Async methods throw ZokoException with an Error property. RequestAdAsync never throws; it returns null when the ad finished and the error otherwise.
Examples#
Ads#
ZokoSDK.Ad.RequestAd(ZokoAdType.Midgame,
adStarted: () => { Time.timeScale = 0; AudioListener.pause = true; },
adFinished: () => { Time.timeScale = 1; AudioListener.pause = false; },
adError: e => { Time.timeScale = 1; AudioListener.pause = false; Debug.Log(e.Code); });async void OnRewardButton()
{
Time.timeScale = 0;
ZokoError error = await ZokoSDK.Ad.RequestAdAsync(ZokoAdType.Rewarded);
Time.timeScale = 1;
if (error == null) GrantReward(); else ShowNoAdMessage();
}Banners#
Add the ZokoGames / Zoko Banner component to a UI RectTransform. Set containerId, choose a size (Responsive or one of the five static sizes) and leave requestOnEnable on. The component reports its on-screen rectangle to the portal, which draws the banner over the canvas. Disable the object to clear the banner.
var screenRect = GetComponent<ZokoBanner>().GetScreenRect();
ZokoSDK.Banner.RequestResponsiveBanner("menu", screenRect, err =>
{
if (err != null) Debug.Log(err.Code);
});Game#
void OnLevelStart() => ZokoSDK.Game.GameplayStart();
void OnLevelEnd() => ZokoSDK.Game.GameplayStop();
ZokoSDK.Game.SetGameContext(new Dictionary<string, object> { { "level", 3 }, { "hard", true } });
ZokoSDK.Game.InviteLink(new Dictionary<string, string> { { "room", roomId } }, (url, err) => { if (err == null) Copy(url); });User#
ZokoSDK.User.GetUserToken((token, err) =>
{
if (err != null) { UseGuestProfile(); return; }
StartCoroutine(SendToServer(token)); // verify on your server, see the user module page
});
ZokoSDK.User.ListFriends(1, 20, (page, err) => { if (err == null) ShowFriends(page.Friends, page.HasMore); });Data (cloud save)#
ZokoSDK.Data is shaped like PlayerPrefs. Reads and writes are synchronous against a preloaded copy, and uploads are batched. Before Init finishes, reads return defaults and writes are dropped with a warning, so only use it after Init. Data.LastError holds the last write error such as dataLimitExceeded. Data.Save() is a no-op kept for parity with PlayerPrefs.Save().
int level = ZokoSDK.Data.GetInt("level", 1);
ZokoSDK.Data.SetInt("level", level + 1);
ZokoSDK.Data.SetFloat("volume", 0.7f);Analytics#
ZokoSDK.Analytics.TrackOrder("provider-name", new Dictionary<string, object> { { "sku", "gems_100" }, { "price", 0.99 } });Purchases are invite-only, see in-game purchases.
Editor simulator#
Outside a browser a simulator answers every call, so Play mode works. Tune it in ZokoSDKSettings: simulate a disabled SDK, an ad that is filled, unfilled or errors, ad duration, an adblocker, a logged-out player, number of friends, mute and chat settings. Simulated cloud save is in PlayerPrefs under zoko-sdk-sim-data; ZokoGames > Clear Simulated Cloud Save wipes it. A demo script ships in the package sample (Package Manager > ZokoGames SDK > Samples > Demo).
Tips#
- Unity WebGL games are disabled on iOS by default. Use compact builds and Brotli or Gzip compression, see optimisation.
ZokoSDK.User.GetUserreturns a user whoseUserIdmust not be trusted on a server; use the token.- Do not block the main thread waiting for callbacks. Use the callbacks or
await.