Przejdź do treści
InstaPlay
Sekcje poradnika

Unity WebGL: the InstaPlay SDK for Unity games

The com.instaplay.sdk 1.3.0 package gives Unity games (2021.3 LTS and newer, WebGL platform) the whole InstaPlay SDK 1.4 in C#: initialization, loading progress, saves, leaderboards, analytics, portal events, the player token for your own server, player changes, ads and sign-in from the game. The SDK itself is JavaScript /_ip/sdk/v1.js on the games domain; the package connects it to C#.

Installation

  1. Download the package: instaplay-unity-1.3.0.tgz (a UPM archive; sizes and sha256 of all archives are in manifest.json). The versioned archive name never changes: a new version is a new file. Put the archive into the project (for example, into Packages/) so the whole team has it, and pick it in Package Manager → “+” → Add package from tarball…. Installation by git URL will come after the package repository is published.
  2. Menu InstaPlay → Установить шаблон WebGL (“Install WebGL template”; the package menus are in Russian for now): the template is copied to Assets/WebGLTemplates/InstaPlay and selected in Player Settings. It includes the SDK, forwards the Unity loader progress to loading.progress and buffers portal events that arrive before Init.
  3. Menu InstaPlay → Рекомендуемые настройки WebGL (“Recommended WebGL settings”) — applies the settings from the table below.

Build settings

Setting Value Why
Compression Format Brotli the games domain serves *.br with Content-Encoding: br (compression)
Decompression Fallback off the browser decompresses; the fallback is extra code and a slower start
Name Files As Hashes on build files are immutable and cached for a long time
Graphics API WebGL 2
Data Caching on a repeated start takes the build data from the browser cache
Initial memory at most 256 MB mobile browsers do not give more; the menu does not set it — set it yourself (Player Settings → Publishing Settings), the menu logs a reminder
WebGL Template InstaPlay without it the SDK is not included

The Recommended WebGL settings menu sets Brotli, turns off Decompression Fallback, turns on Name Files As Hashes and Data Caching and leaves only WebGL 2. The InstaPlay template is a single index.html; there is no TemplateData/ folder in it.

External requests go only to game network addresses: fonts and third-party analytics fail check R07. Do not use WebGL templates with an offline cache (Service Worker, PWA) — Service Workers are forbidden on the games domain. Assets above the build limit come from your CDN via UnityWebRequest or Addressables; .loader.js and .framework.js stay in the build (large games).

Code

using InstaPlaySdk;
using UnityEngine;

public class Boot : MonoBehaviour
{
    void Start()
    {
        // Subscribe before Init: events that arrived during loading are delivered right after it.
        InstaPlay.OnPause += reason => Time.timeScale = 0f;
        InstaPlay.OnResume += () => Time.timeScale = 1f;

        InstaPlay.Init(info =>
        {
            // info.environment: instaplay | local | disabled; info.locale: ru | en
            if (InstaPlay.IsPaused) Time.timeScale = 0f; // the game may start under a portal window
            InstaPlay.Saves.Get("progress", entry =>
            {
                if (entry.found) Progress.Load(entry.dataJson);
                InstaPlay.Ready(); // the game accepts input — the portal removes its loading screen
            }, error => InstaPlay.Ready()); // Ready in any case, or after 20 s the portal offers a restart
        });
    }

    public void StartRound() => InstaPlay.GameplayStart();

    public void FinishRound(int score)
    {
        InstaPlay.GameplayStop();
        InstaPlay.Saves.Set("progress", Progress.ToJson());
        InstaPlay.Leaderboard.Submit("main", score, r => Debug.Log(r.Rank("all")));
    }
}

Progress here is your own game state class. OnPause fires for every reason (a portal window, a hidden tab), OnResume fires once when no reasons remain; the Samples~/Basic sample shows how to restore the previous timeScale. Errors come to the second callback as InstaPlayError (Code: offline, version_conflict, rate_limited with RetryAfterMs…); without it the error is logged. Call Ready() even when reading the save fails (offline, an error): otherwise the loading screen stays and after 20 s the portal offers the player a restart. A pause that was already on at Init (the player opened a portal window while Unity was loading) does not fire OnPause — check IsPaused in the Init callback.

API

C# SDK v1
Init, Info, Environment, Locale, IsInitialized init
Session, Country (Info.session, Info.country, Info.HasCountry) session (1.1), country (1.2) in the init result
LoadingProgress, Ready, GameplayStart, GameplayStop, HappyMoment lifecycle
Level.Started / Completed / Failed level.*
Player.Get, Player.GetToken player, the token for your own server (1.1)
Saves.Get / GetMany / Set / Remove / Clear / Flush, Saves.OnConflict saves
Leaderboard.Submit, Leaderboard.Get leaderboards
Analytics.Event, Analytics.Flush analytics
Ads.Interstitial, Ads.Rewarded, Ads.Available ads (1.3)
IsSupported, GetServerTime isSupported, getServerTime
OnPause, OnResume, OnMute, OnUnmute, OnVisibility, OnLocaleChanged, OnPlayerChanging portal events, playerChanging (1.1)
IsPaused, IsMuted — initial values from Init, then by events system.pause, system.muted (1.1)

Save data is a JSON string (JsonUtility.ToJson); read it with entry.Data<T>() or entry.dataJson. AutoPauseAudio (on by default) mutes audio on pause and on portal mute; stop game time yourself in OnPause.

Your own game server. InstaPlay.Player.GetToken(token => …, error => …) — a portal-signed player token (JWT ES256, 10 minutes, the SDK caches it): exchange it for your server's session (player token). Without the token feature (IsSupported("token") == false, outside the portal, in the editor) — the not_supported error. OnPlayerChanging(reason) (login, logout, switch) — in ~1.5 s the portal restarts the game with another player: send your data to your server; the SDK flushes cloud saves itself.

Sign-in from the game (SDK 1.4, package 1.3.0). InstaPlay.Player.Login(onDone, onError) opens the portal sign-in window over the game; the outcome is a LoginResult (status: signed_in, already_signed_in, cancelled; player). Show the “Save progress” button to a guest when IsSupported("login") and call Login right in the press handler — otherwise gesture_required. The example, the editor stub (stubLoginOutcome) and all errors are in the package README (inside the instaplay-unity-1.3.0.tgz archive); rules and patterns — Player and sign-in.

Verbose SDK log. With the InstaPlay template the template itself initializes the SDK before Unity loads, so Init(debug: true) changes nothing: set var IP_DEBUG = true in your copy of the template, Assets/WebGLTemplates/InstaPlay/index.html. With your own template (that does not call init) Init(debug: true) works.

Ads

Ads are shown by the portal; the game only asks (ads in your game):

// Between levels — after GameplayStop (during gameplay the answer is gameplay_active).
InstaPlay.GameplayStop();
InstaPlay.Ads.Interstitial("level_end", r => LoadNextLevel(), null, "next");

// For a reward — only on the player's button press; show the button when the portal is ready.
InstaPlay.Ads.Available("rewarded", a => extraLifeButton.SetActive(a.available));
public void OnExtraLifePressed() => InstaPlay.Ads.Rewarded("extra_life", r =>
{
    if (r.rewarded) GiveExtraLife(); // your server verifies r.grantToken
    else Debug.Log("no reward: " + r.reason); // declined, dismissed, no_fill, cooldown…
});
Type Fields
AdResult shown, reason (empty or a reason)
RewardResult rewarded, reason, grantToken, grantId, grantExpiresAt, HasGrant
AdAvailability available, reason, retryAfterMs

Normal outcomes (no ad, a cooldown, the player declining) arrive in the first callback with false and a reason; the second one (InstaPlayError) gets protocol errors only (rate_limited, timeout). During an ad OnPause("ad") and OnMute arrive — AutoPauseAudio mutes the sound itself; stop game time as for any pause. grantToken is the signed reward for your server (reward verification); empty — the reward is unsigned (preview, editor).

Editor

In Play Mode the package uses a stub: local mode, saves and leaderboards in memory, calls logged. Simulate portal events with the InstaPlay → Заглушка: … (“Stub: …”) menu items, including a player change; Player.GetToken in the editor is not_supported, as the SDK outside the portal.

Ads in the editor: select the InstaPlayBridge object (the DontDestroyOnLoad scene in Play Mode) and set the outcome in the inspector — Stub Ad Outcome: Completed (shown; the reward is unsigned), NoFill, Dismissed (closed a rewarded ad early), Declined (declined in the card), Disabled (no ads) — and the length Stub Ad Seconds. “Shown” sends OnPause("ad") and OnMute, and after that time OnResume and OnUnmute; an interstitial between GameplayStart and GameplayStop gets gameplay_active.

Progress and the page address

On WebGL, Application.persistentDataPath and PlayerPrefs live in IndexedDB under a key derived from the page address. Every new build (/<hash>/) and every game network change (/<hash>-<revision>/) changes the address, so progress in persistentDataPath “disappears” after a game update. Keep progress in cloud saves — InstaPlay.Saves (saves): they do not depend on the address, device or browser. PlayerPrefs are fine only for settings you do not mind losing.

Check and upload

  1. Build WebGL into a folder (index.html, Build/).
  2. Run it like the portal does: instaplay test ./WebGL — the portal emulator and headless Chromium on desktop and mobile (CLI).
  3. Zip the folder contents (so index.html is at the zip root) and upload it in the dashboard or with instaplay publish (Uploading a build).