# 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 asynchronous method has a callback form and an `...Async` form returning a `Task`. Cloud save (`Data`), `Store.IsAvailable`, `Store.SetSandbox`, `Game.Settings` and `Game.InviteParams` are synchronous. Terms such as "midgame ad" are in the [glossary](https://docs.zokogames.com/getting-started/glossary).

> [!NOTE]
> Status (plugin 1.7.0, run on 2026-11-23): built and run with Unity 6000.3.28f1. The published package compiles with no warnings, and a WebGL build ran in local mode and on the production portal (console Preview), passing all 12 areas. Store purchases, two-player rooms, the sign-in prompt, kids mode, offline and mobile browsers are not tested yet. Unity 2021.3 to 2023 are only compiled with a real C# compiler against stubs of the Unity API. If something fails on import, send the Unity version and the exact error to [support](https://docs.zokogames.com/business/support).

## Install

Download the Unity plugin: [/sdk-engines/zokogames-unity-1.7.0.zip](https://www.zokogames.com/sdk-engines/zokogames-unity-1.7.0.zip) (the same files as the folder in the repository).

[/sdk-engines/unity.zip](https://www.zokogames.com/sdk-engines/unity.zip) is always the latest version. Checksums: [`/sdk-engines/SHA256SUMS`](https://www.zokogames.com/sdk-engines/SHA256SUMS). Index of every engine package with its version, size and SHA-256: [`/sdk-engines/engines.json`](https://www.zokogames.com/sdk-engines/engines.json).

1. **Window > Package Manager > Add package from disk**, then choose `package.json` from the plugin folder (`packages/sdk-engines/unity/package.json`, or the same file inside the unzipped packager output, see the [overview](https://docs.zokogames.com/engines/overview#getting-the-plugin)). Copying the folder into your project's `Packages/` folder (an embedded package) also works. From 1.6.1 every file ships with its `.meta` file, so the package should also import from your own git repository or a tarball, which Unity treats as read-only (not yet tried in an editor). The package depends on `com.unity.ugui`, which new Unity projects already include.
2. Run **ZokoGames > Install WebGL Template**. It copies the template to `Assets/WebGLTemplates/ZokoGames` and sets Player Settings to `PROJECT:ZokoGames`. The template loads `https://sdk.zokogames.com/zokogames-sdk-v1.js` before the Unity loader, reports the engine download to the portal's loading bar (`loadingStart`, `loadingProgress`, `loadingStop`) and keeps the canvas id `unity-canvas`. With your own template, add the script tag to `<head>` before the Unity loader and keep that canvas id.
3. Optional: **ZokoGames > Create Simulator Settings** creates `Assets/Resources/ZokoSDKSettings.asset` to tune the editor simulator.
4. Optional: import the **Demo** sample from the Package Manager (`ZokoDemo.cs` touches every module with one key per module; `ZokoStoreExample.cs` is a purchase flow: catalogue, buy, consume, inventory, error codes).

The bridge is `Plugins/WebGL/ZokoSDK.jslib`. It calls the JavaScript SDK and answers a hidden `ZokoSDKBridge` GameObject through `SendMessage`, so leave the `.jslib` in `Plugins/WebGL/` and do not rename that GameObject.

## Which path

| You are | Do this |
| --- | --- |
| A WebGL studio with a shipping game | Install the package and template, call `InitAsync` first, wrap your existing ad, save and score calls in `ZokoSDK`, set Brotli, upload. |
| Starting a game for the portal | Same, and keep the first scene under the [initial download limit](https://docs.zokogames.com/guides/first-frame); load the rest with Addressables. |

## A working boot script

One MonoBehaviour that covers init, a midgame ad, a rewarded ad, gameplay start and stop, save and load, and a leaderboard score. Put it in your first scene.

```csharp
using UnityEngine;
using ZokoGames;

public class ZokoBoot : MonoBehaviour
{
    float _savedTimeScale = 1f;
    bool _adPaused;

    async void Start()
    {
        try { await ZokoSDK.InitAsync(); }                 // throws ZokoException when the SDK script is missing
        catch (ZokoException e) { Debug.LogWarning("ZokoGames init failed: " + e.Code); }

        // Environment is "local", "zokogames" or "disabled"; IsSimulated is true in the editor.
        Debug.Log("ZokoGames: " + ZokoSDK.Environment + (ZokoSDK.IsSimulated ? " (simulated)" : ""));
        if (!ZokoSDK.IsAvailable) { StartGame(); return; }  // the game must run without the portal

        // Audio needs no code: the SDK applies the portal's mute (Ad.FollowPortalMute) and mutes during ads (Ad.MuteAudioDuringAds).

        int level = ZokoSDK.Data.GetInt("level", 1);        // load: synchronous, after Init only
        StartGame();
    }

    // Call when the player takes control, and when play stops (pause menu, game over, level end).
    public void OnPlayStart() { if (ZokoSDK.IsAvailable) ZokoSDK.Game.GameplayStart(); }
    public void OnPlayStop()  { if (ZokoSDK.IsAvailable) ZokoSDK.Game.GameplayStop(); }

    // Pause on adStarted, resume on adFinished AND adError. RequestAdAsync never throws.
    public async void ShowMidgame() { await ShowAd(ZokoAdType.Midgame); }

    public async void OnRewardButton()
    {
        bool finished = await ShowAd(ZokoAdType.Rewarded);
        if (finished) GrantReward();                        // reward only after adFinished
    }

    async System.Threading.Tasks.Task<bool> ShowAd(ZokoAdType type)
    {
        if (!ZokoSDK.IsAvailable) return false;
        ZokoError error = await ZokoSDK.Ad.RequestAdAsync(type, adStarted: PauseForAd);
        ResumeAfterAd();                                    // runs for finished, unfilled, adCooldown, adblock ...
        if (error != null) Debug.Log("no ad: " + error.Code);
        return error == null;
    }

    void PauseForAd()
    {
        if (_adPaused) return;
        _adPaused = true;
        _savedTimeScale = Time.timeScale;
        Time.timeScale = 0f;
    }

    void ResumeAfterAd()
    {
        if (!_adPaused) return;
        _adPaused = false;
        Time.timeScale = _savedTimeScale;
    }

    // Save: synchronous against a preloaded copy; uploads are batched.
    public void SaveProgress(int level)
    {
        ZokoSDK.Data.SetInt("level", level);
        if (ZokoSDK.Data.LastError != null) Debug.LogWarning(ZokoSDK.Data.LastError.Code); // e.g. dataLimitExceeded
    }

    // Leaderboard: needs a signed-in player and the board enabled in the console.
    public void SubmitScore(double score)
    {
        ZokoSDK.User.GetUser((user, err) =>
        {
            if (err != null || user == null) return;        // guests are not ranked
            ZokoSDK.User.SubmitScore("", score, e => { if (e != null) Debug.Log(e.Code); });
        });
    }

    void StartGame() { }
    void GrantReward() { }
}
```

You do not write audio code for the portal. The SDK mutes `AudioListener` while an ad plays and restores it afterwards (`ZokoSDK.Ad.MuteAudioDuringAds`), and applies the portal's mute setting to `AudioListener.pause` after init and on every change (`ZokoSDK.Ad.FollowPortalMute`); both are on by default. Set `FollowPortalMute` to `false` before `Init` if you want to handle `Game.SettingsChanged` yourself. Pausing the game itself (`Time.timeScale` above) stays your job.

About the leaderboard line: `SubmitScore(encryptedScore, score)` sends whatever string you give it. A board **with** an encryption key counts only a correctly encrypted payload (see [leaderboards](https://docs.zokogames.com/sdk/leaderboards#client-submission)), and no engine wrapper ships an encryption helper, so the empty string above works only for a board **without** a key (the plain score is then validated against the board rules). For a keyed board, either encrypt in C# yourself (AES-256-GCM with the additional data `zoko-score-v1|<userId>|<gameId>`, where `ZokoUser.UserId` holds the player id; check that your Unity version has an AES-GCM implementation that works in WebGL) or compute scores on your own server and use the server API.

## Initialise and state

| Member | Meaning |
| --- | --- |
| `ZokoSDK.Init(cb)` / `InitAsync()` | Once, first. Safe to call repeatedly. Other calls before it finishes fail with `sdkNotInitialized`; if the call itself fails (for example `sdkNotLoaded`) the SDK stays uninitialised. |
| `ZokoSDK.IsInitialized` | `Init` completed. |
| `ZokoSDK.IsAvailable` | Initialised and not `disabled`. |
| `ZokoSDK.Environment` | `"local"`, `"zokogames"` or `"disabled"`. |
| `ZokoSDK.IsQaTool` | Running in the QA tool. |
| `ZokoSDK.Version` | The JavaScript SDK release the wrapper was written against. The published package (1.7.0) reports `"1.7.0"`. Plugin versions are separate from the SDK version, and the plugins are repacked at the next plugin release. |
| `ZokoSDK.IsSimulated` | The editor or native simulator is answering (the build is not a WebGL player). |

## Mapping

<!-- search: headings-only -->

| Module | JavaScript | Unity |
| --- | --- | --- |
| Ad | `ad.requestAd(type, cbs)` | `Ad.RequestAd(ZokoAdType.Midgame, adStarted, adFinished, adError)` or `Ad.RequestAdAsync(type, adStarted)` |
| 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`, `loadingProgress(0..100)`, `happytime` | `Game.LoadingStart()`, `Game.LoadingStop()`, `Game.LoadingProgress(percentage)`, `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 | `isOffline`, offline listeners | `Game.IsOffline`, event `Game.OfflineChanged` (`Action<bool>`) |
| Game | rooms and invites | `Game.UpdateRoom(ZokoRoomUpdate)`, `Game.LeftRoom()`, `Game.InviteLink(params, cb)`, `Game.ShowInviteButton(params, cb)`, `Game.HideInviteButton()`, `Game.InviteParams`, `Game.GetInviteParam(key)`, `Game.IsInstantMultiplayer` (alias `IsInstantJoin`), 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)` / `SubmitScoreAsync` |
| Data | `getItem` ... `clear` | `Data.GetItem/SetItem/RemoveItem/Clear`, plus `GetString/SetString/GetInt/SetInt/GetFloat/SetFloat/HasKey/DeleteKey/DeleteAll` |
| Store | `store.isAvailable`, `getCatalogItems`, `getPlayerInventory` | `Store.IsAvailable`, `Store.GetCatalogItemsAsync(limit, offset)`, `Store.GetPlayerInventoryAsync(limit, offset)` |
| Store | `buyItem`, `consumeItem`, `setSandbox` | `Store.BuyItemAsync(sku)`, `Store.ConsumeItemAsync(sku, qty)`, `Store.SetSandbox(bool)` |
| Store | `getPurchaseToken` (`user.getXsollaUserToken` is the deprecated name) | `Store.GetPurchaseTokenAsync()` |
| Errors | `ERROR_CODES` | `ZokoErrorCodes.Store.PurchaseCancelled` etc.; `ZokoError.Is(code)` |
| Achievements | `achievements.list()`, `achievements.unlock(key)`, `onUnlock` | `Achievements.List(cb)`, `Achievements.Unlock(key, cb)` (or `...Async`), event `Achievements.OnUnlock`; see [achievements](https://docs.zokogames.com/sdk/achievements) |
| Analytics | `trackOrder(provider, order)` | `Analytics.TrackOrder(provider, order, done)` |
| Analytics | `track(name, params)` (1.7.0) | `Analytics.Track(name, params, done)` |

Errors arrive as `ZokoError` (`Code`, `Message`, `ContainerId`). The `...Async` methods throw `ZokoException` (`Error`, `Code`). `RequestAdAsync` never throws: it returns `null` when the ad finished and the error otherwise.

**Kids mode.** Since version 1.5.0 the wrapper exposes it: `ZokoSDK.Game.Settings.KidsMode` is true when the game runs in kids mode (a game with the kids flag, or a player in kids mode); hide chat, rooms, sign-in prompts and shop screens then. A portal that does not send the field gives false, so also keep honouring `ZokoSDK.Game.Settings.DisableChat`, which the portal sets to true in the same cases. To test it, switch on `ZokoSDKSettings.kidsMode` in the simulator (it also turns chat off, as the portal does). See [kids mode](https://docs.zokogames.com/guides/kids-mode).

## Room data channel

Added in SDK 1.3.0. The room data channel lets the players of one room exchange small JSON messages and share a tiny state that only the host writes, so a simple multiplayer game needs no server of its own. It is for game data, not text chat. It exists after `updateRoom` (or after joining from an invite) and ends with `leftRoom`, needs a signed-in player and a portal with realtime enabled (otherwise `roomUnavailable`), and has these limits: 8 KB per message or patch, 20 messages per second, 64 KB of state, state keys of 1 to 40 characters of `A-Z a-z 0-9 _ . : -`. Messages are never echoed back to their sender on the portal; the first player in the room is the host. The full rules and error codes (`notInRoom`, `notHost`, `payloadTooLarge`, `stateTooLarge`, `unknownMember`, `rateLimited`, `roomUnavailable`) are in the [game module](https://docs.zokogames.com/sdk/game#room-data-channel) and the [multiplayer guide](https://docs.zokogames.com/guides/multiplayer-invites#6-exchange-game-data-in-the-room).

`ZokoSDK.Game.Room` carries it. Pass a `Dictionary`, a `List`, a string, a number or a bool, a JSON string (`SendJson`) or a `[Serializable]` object (`SendTyped<T>`, which uses `JsonUtility`). Events are raised on the main thread. In the editor and in non-WebGL players the simulator is one room with one member that receives its own messages and state changes, so a single instance can run the flow.

| JavaScript | Unity |
| --- | --- |
| `room.send(data, { to })` | `Game.Room.Send(data, done)`, `SendTo(memberId, data, done)`, `SendJson(json, to, done)`, `SendTyped<T>(obj, to, done)`, `SendAsync(data, to)` |
| `room.onMessage(cb)` | event `Game.Room.MessageReceived` (`ZokoRoomMessage`: `From`, `Direct`, `Seq`, `Ts`, `Data`, `Json`, `As<T>()`) |
| `room.setState(patch)` | `Game.Room.SetState(patch, done)`, `SetState(key, value, done)`, `SetStateJson(json, done)`, `SetStateAsync(patch)` |
| `room.getState()`, `room.onState(cb)` | `Game.Room.State`, `GetState(key)`, `GetState<T>()`, `GetStateJson()`; event `StateChanged(state, ZokoRoomStateChange)` |
| `room.members()`, `room.onMembers(cb)` | `Game.Room.Members` (`ZokoRoomMember`: `Id`, `Username`, `ProfilePictureUrl`); event `MembersChanged` |
| `room.isHost()`, `room.onHostChange(cb)`, `room.selfId` | `Game.Room.IsHost`; event `HostChanged(hostId, isHost)`; `Game.Room.SelfId` |
| `room.addLeftListener(cb)` (1.7.0) | event `Game.Room.Left(reason, roomId)` |
| `room.onError(cb)` | event `Game.Room.Error` (`ZokoError`); codes in `ZokoErrorCodes.Room` |

```csharp
[System.Serializable] class Move { public int cell; public string mark; }

async void StartMatch()
{
    await ZokoSDK.InitAsync();
    ZokoSDK.Game.Room.MessageReceived += m => Board.Place(m.As<Move>());
    ZokoSDK.Game.Room.HostChanged += (hostId, isHost) => { if (isHost) ZokoSDK.Game.Room.SetState("turn", "X"); };
    ZokoSDK.Game.Room.Error += e => Debug.LogWarning("room: " + e);
    await ZokoSDK.Game.UpdateRoomAsync(new ZokoRoomUpdate { RoomId = "match-1", IsJoinable = true });
}

void OnCellClicked(int cell) => ZokoSDK.Game.Room.SendTyped(new Move { cell = cell, mark = "X" });
```

## Banners

Add **Add Component > ZokoGames > Zoko Banner** to a UI `RectTransform`. Set `containerId`, choose a `size` (`Responsive`, `S728x90`, `S300x250`, `S320x50`, `S468x60` or `S320x100`) and leave `requestOnEnable` on. The component reports its on-screen rectangle to the portal, which draws the banner over the canvas; disabling the object clears the banner. Request banners on menu screens, never in play.

```csharp
ZokoSDK.Banner.RequestResponsiveBanner("menu", GetComponent<ZokoBanner>().GetScreenRect(), err =>
{
    if (err != null) Debug.Log(err.Code);
});
```

## Purchases

```csharp
if (ZokoSDK.Store.IsAvailable)
{
    try
    {
        var catalog = await ZokoSDK.Store.GetCatalogItemsAsync(limit: 20);
        string bought = await ZokoSDK.Store.BuyItemAsync(catalog[0].Sku);
        string token = await ZokoSDK.Store.GetPurchaseTokenAsync();   // send to your server and verify there
    }
    catch (ZokoException e) when (e.Error.Is(ZokoErrorCodes.Store.PurchaseCancelled)) { }
}
```

Verify ownership on your server (see [in-game purchases](https://docs.zokogames.com/sdk/purchases)). The sample `ZokoStoreExample` is the full flow.

## Addressables and custom builds

Keep the first scene small and load the rest after the player can act. Addressables work on the portal under three rules.

1. **Ship the content inside the build.** Set the Addressables **Build Path** to a folder under `StreamingAssets` (for example `Assets/StreamingAssets/aa`, which is the default "local" group) and the **Load Path** to `{UnityEngine.AddressableAssets.Addressables.RuntimePath}`. The bundles then travel in the zip and are served from the same build folder, with relative paths. Do not point the remote load path at another host: the validator reports external hosts (`external_url`, `origin_unknown`) and a game that needs one cannot be saved for [offline play](https://docs.zokogames.com/guides/offline-play).
2. **Count the files.** Every bundle is a file in the 1,500 file budget and counts toward 250 MB. Group assets by scene or level, not one bundle per asset, and keep bundle names to ASCII with consistent letter case (the host is case sensitive, see [relative paths](https://docs.zokogames.com/requirements/technical#relative-paths-only)).
3. **Load after the first frame.** Call `Game.LoadingStart()` and `LoadingProgress(p)` from your own loading screen while `Addressables.LoadSceneAsync` runs, then `LoadingStop()` when the player can act. Only the first scene counts toward the [initial download](https://docs.zokogames.com/guides/first-frame).

A custom WebGL template works if it keeps the canvas id `unity-canvas` and loads `https://sdk.zokogames.com/zokogames-sdk-v1.js` before the Unity loader (see Install). Copy the ZokoGames template and edit it rather than starting from the default one. A custom build script (for example a CI job calling `BuildPipeline.BuildPlayer`) only has to set the same options as the table below and write the result to a folder you zip with `index.html` at the archive root.

## Common issues

<!-- search: headings-only -->

| Symptom | Cause and fix |
| --- | --- |
| Blank canvas, console shows `SharedArrayBuffer is not defined` | A multithreaded build. Turn WebGL threading off and rebuild (see **Threading** in the table below). |
| Loader stops at "Unable to parse Build/....framework.js.br" | A `.br` file served without `Content-Encoding`, usually a local static server. Test on `localhost` with a server that sends the header, or build with compression Disabled for local tests. On the portal the header is set for you. |
| 404 for a file that exists on your disk | Letter case differs from the reference (`case_mismatch`). Names are case sensitive on the host. |
| Works in the Editor, `sdkNotLoaded` in the build | The WebGL template is not ZokoGames. Run **ZokoGames > Install WebGL Template** and rebuild. |
| Save data lost between sessions | You wrote to `PlayerPrefs` only. In a WebGL player it lives in the browser's IndexedDB for that origin. Mirror the keys into cloud save with `ZokoSDK.Data.PushPlayerPrefs` and restore them with `PullPlayerPrefs` right after `InitAsync`. |
| Copy button does nothing | Browsers allow copying only from a click or tap handler. Call `ZokoSDK.CopyToClipboard(text)` there, not from `Update()` or after an `await`. |
| Out-of-memory crash on phones | The initial memory is too large or one texture or bundle is huge. Lower the initial memory, compress textures (ASTC), load content in pieces with Addressables. |

## PlayerPrefs mirror and clipboard

`PlayerPrefs` cannot tell the type of a key, so you list the keys and their types once:

```csharp
static readonly Dictionary<string, ZokoPrefType> Keys = new Dictionary<string, ZokoPrefType>
{
    { "playerName", ZokoPrefType.String },
    { "level", ZokoPrefType.Int },
    { "volume", ZokoPrefType.Float },
};

// After InitAsync: bring cloud save into PlayerPrefs (a key already there is kept; pass true to let cloud save win).
ZokoSDK.Data.PullPlayerPrefs(Keys);

// When the player saves or a level ends: copy PlayerPrefs into cloud save.
ZokoSDK.Data.PushPlayerPrefs(Keys);

// From a click handler: copy an invite code.
bool copied = ZokoSDK.CopyToClipboard(inviteCode);
```

Both calls skip keys that do not exist and return how many keys they moved. They respect the 1 MB cloud save limit like every other `Data` call (check `ZokoSDK.Data.LastError`).

## WebGL export settings that matter

<!-- search: headings-only -->

| Setting | What to choose, and why |
| --- | --- |
| Player Settings > Publishing Settings > **Compression Format** | **Brotli** or **Gzip**. Unity then writes `.br` or `.gz` files. The game origin gives any `.br` or `.gz` file the matching `Content-Encoding` header, so the browser decodes it and the Unity loader needs no JavaScript decompression. Use one format for the whole build. |
| **Decompression Fallback** | Leave **off**. It is for hosts that cannot set `Content-Encoding`; the portal can, and the fallback makes the loader larger and slower. |
| Compression **Disabled** | Works, but the download is larger. |
| Legacy `.unityweb` files | Avoid them. They get no `Content-Encoding`, so the loader unpacks them in JavaScript and the game starts slower (validator warning `unity_unityweb`). Mixing `.br` and `.gz` or leaving some Build files uncompressed also warns (`unity_mixed_compression`, `unity_compression_mismatch`). |
| Resolution and Presentation > **WebGL Template** | **ZokoGames**. The canvas fills the frame (CSS 100 percent), so use a Canvas Scaler set to **Scale With Screen Size**, not a fixed pixel size. |
| Other Settings | Managed Stripping Level High, Strip Engine Code on, IL2CPP "Faster (smaller) builds", ASTC for mobile or DXT textures. Avoid unused packages and large StreamingAssets. |
| **Memory** | The portal frame limits what a phone can allocate. Keep the initial memory small and let it grow; load big content through Addressables after the first scene. Unity games are off on iOS by default (tick **Tested and works well on iOS** in the console only after testing, see [mobile](https://docs.zokogames.com/guides/mobile)). |
| **Threading** | Off. Game pages are served without COOP/COEP headers, so the page is not cross-origin isolated and `SharedArrayBuffer` is unavailable; a threaded WebAssembly build cannot run. Disable multithreading (WebGL threading, and native C/C++ threads in plugins). A threaded build shows `SharedArrayBuffer is not defined` or a blank canvas. |
| Download budget | 1,500 files, 250 MB unpacked, about 50 MB initial download (20 MB for mobile). The estimate uses the uncompressed size, so compression does not rescue an oversized build. |

Other export notes:

- **Audio unlock.** Browsers keep WebAudio suspended until the first click, tap or key press. Unity resumes it on the first input, so show a "tap to play" screen before music instead of starting audio in `Start()`.
- **Fullscreen.** Prefer the fullscreen button in the portal's frame bar: it fullscreens the whole frame (the portal keeps its own bar and handles phone orientation). The frame carries `allow="fullscreen"`, so `Screen.fullScreen = true` is permitted, but it fullscreens the game's own canvas and the portal cannot restore its layout the same way; do not add a competing button.
- **Single thread.** Never use `Task.Wait()` or `.Result` on WebGL: it deadlocks. `await` and the callback forms are fine.
- **Loading.** The template already reports the engine download. For your own first scene call `Game.LoadingStart()`, `LoadingProgress(p)` and `LoadingStop()` when the player can act.

Upload: build for WebGL, zip the **contents** of the build folder so `index.html` is at the archive root, and upload it in the developer console. Run the [Preview tool](https://www.zokogames.com/preview) first.

After an ad, a sign-in or account-link prompt or a checkout, keyboard focus goes back to the game frame and its canvas by itself, so the player's keys work again without a click.

## Chat reports, screenshots and storage mirror

Since SDK 1.4.0 the wrapper binds three more calls.

```csharp
ZokoSDK.Game.ReportChat(new ZokoChatReport { ReportedName = "Trixie", Message = "buy gold", Reason = ZokoChatReportReason.Spam, RoomId = roomId }, err => { });
ZokoSDK.Game.SetScreenshotProvider(() => MyCamera.RenderToTexture()); // optional; a default end-of-frame capture is registered at init
ZokoSDK.Data.MirrorLocalStorage(prefix: "save_");                      // only for JavaScript-side localStorage
```

`ReportChat` sends one message to the portal's moderators (name 1 to 40 characters, message 1 to 500); it fails with `invalidArgument`, `rateLimited` or `unexpectedError`. The screenshot provider returns a `Texture2D` (or null for no picture) when the portal's feedback form asks; the wrapper encodes it as JPG and answers within the SDK's 3 second limit. Unity `PlayerPrefs` on WebGL live in IndexedDB, not `localStorage`, so the mirror never sees them: use `Data.PushPlayerPrefs` for those. In the editor all three calls run against the simulator.

## Ad rules

There are no prerolls: your game cannot request an ad before it starts. Midgame is the only interstitial type, so an interstitial or commercial break from another platform becomes a midgame ad (`ZokoAdType.Midgame`); the only other type is `rewarded`. In local mode (testing on `localhost`, outside the portal) a midgame request fails with the error code `adCooldown` (your `RequestAdAsync` returns it) until your game has called `ZokoSDK.Game.GameplayStart()` or 30 seconds of visible page time have passed. On the portal the first midgame ad needs `ZokoSDK.Game.GameplayStart()` first as well, so call it when the player takes control (a game that never calls it gets midgame ads 30 seconds after play begins). Rewarded ads are not held back by this. Details: [ads reference](https://docs.zokogames.com/sdk/ads#gameplay-first) and [ads guide](https://docs.zokogames.com/guides/ad-monetisation).

## Test locally

- **In the Editor and in any non-WebGL player** the built-in simulator answers (`ZokoSDK.IsSimulated` is true), so Play mode works. Tune it in `ZokoSDKSettings`: simulate a disabled SDK, ad behaviour (Fill, NoFill, Error), ad duration (default 1.5 seconds), an adblocker, a logged-out player, friend count, mute and chat, offline, and store availability. Simulated cloud save lives in `PlayerPrefs` under `zoko-sdk-sim-data`; **ZokoGames > Clear Simulated Cloud Save** wipes it. Calls always answer asynchronously, like the browser.
- **Difference to remember.** The simulator does not enforce the three-minute midgame cooldown that the portal and the browser's local mode enforce (`adCooldown`), and it only logs banner requests. Test both in a web build.
- **A WebGL build on `localhost`.** Serve the build folder from a local web server on `localhost`; the SDK then runs its own [local mode](https://docs.zokogames.com/getting-started/local-testing) (a three-second overlay per ad, fake players, `localStorage` saves, a test store, `?sdk_debug=true`, `?ad_response=unfilled`). Brotli builds only load over HTTPS or `localhost`, because browsers accept `Content-Encoding: br` only in a secure context, and a plain static server must also send that header for `.br` files. If yours does not, build with compression Disabled for local tests.
- **Then the real thing.** Open the [Preview tool](https://www.zokogames.com/preview) with your local address, and run the uploaded build in the console's build preview.

## Known pitfalls

<!-- search: headings-only -->

- **Game stops while an ad plays or the tab is in the background.** Set `Application.runInBackground = true`. The SDK pauses `AudioListener` during ads and restores it afterwards (`ZokoSDK.Ad.MuteAudioDuringAds`).
- **`sdkNotLoaded` or "ZokoGames is undefined".** The page has no SDK script tag. Use the ZokoGames template or add the tag before the Unity loader.
- **`.jslib` ignored.** It must stay in `Plugins/WebGL/` and the build target must be WebGL.
- **Every call fails with `sdkNotInitialized`.** Wait for `Init` to finish; a failed `Init` leaves the SDK uninitialised.
- **Game stays paused or silent after an ad.** Resume on `adError` as well as `adFinished`: unfilled ads, `adCooldown` and ad blockers all end in `adError`. `RequestAdAsync` returns in every case, so the code after `await` is the safe place.
- **`Task` never completes.** The call was awaited off the main thread.
- **Banner empty in the Editor.** The simulator only logs banner requests.
- **`UserId` is not proof of identity.** `ZokoUser.UserId` is the raw id from the client; verify the [token](https://docs.zokogames.com/sdk/user#tokens) on your server.
- **Do not block the main thread** waiting for callbacks.

## Next

- Check your build against the [build validation rules](https://docs.zokogames.com/requirements/build-validation) and the [launch checklist](https://docs.zokogames.com/requirements/checklist).
- Upload and publish: [submission walkthrough](https://docs.zokogames.com/getting-started/submission-walkthrough).
- Other engines and shared rules: [engines overview](https://docs.zokogames.com/engines/overview).
