# Unity WebGL

Publish a Unity WebGL game on Glint: install Glint.jslib and Glint.cs, add the Glint component, use the Foundry WebGL template, build uncompressed, and call the SDK from C#.

The Unity adapter connects a Unity WebGL build to the Glint SDK. It has a JavaScript plugin, a C# component you call from your scripts, and a WebGL template that loads the SDK before Unity starts.

## What's in the Adapter

```bash
glint init unity unity-adapter
```

| File | What it is |
| --- | --- |
| `Glint.jslib` | The WebGL plugin that calls the SDK in the browser. |
| `Glint.cs` | The `Glint` component (namespace `GlintSdk`) your C# code calls. |
| `WebGLTemplate/index.html` | The page Unity builds from. |
| `WebGLTemplate/glint.js` | The browser build of the SDK. |
| `glint.json` | A starter manifest with `"engine": "unity"` and `"webgl2": true`. |

## Install the Plugin

1. Copy `Glint.jslib` and `Glint.cs` into `Assets/Plugins/WebGL/Glint/`.
2. Copy the `WebGLTemplate` folder to `Assets/WebGLTemplates/Glint/`, so the folder holds `index.html` and `glint.js`.
3. Copy `glint.json` into `Assets/WebGLTemplates/Glint/` too, and edit its `name` and `version`. Unity copies every file in the template folder into each build, so the manifest lands next to `index.html`.

## Add the Glint Component

Create an empty GameObject named `Glint` in your first scene and add the **Glint** component. It keeps itself alive across scene loads, and a second copy destroys itself. Reach it from any script as `Glint.Instance`.

The plugin sends events back to this GameObject by name, so keep it active and don't rename it while the game runs.

In the Editor, every call does nothing, `LoadSlot()` returns an empty slot, and `OnReady` fires inside the component's `Awake()` with a placeholder player. In a WebGL build, `OnReady` fires once the SDK connects.

## Select the WebGL Template

In **Project Settings > Player > Resolution and Presentation**, on the WebGL tab, pick the **Glint** template. The template:

- fills Glint's frame with the Unity canvas;
- loads `./glint.js`, then Unity's loader;
- starts the SDK and passes Unity's loading progress to Glint's loading bar, up to 95%;
- caps Unity's pixel ratio at `Math.min(2, maxDpr)`;
- calls `sdk.lifecycle.ready()` when Unity has loaded.

```html
<canvas id="unity-canvas" tabindex="-1"></canvas>
<script src="./glint.js"></script>
<script src="./Build/{{{ LOADER_FILENAME }}}"></script>
<script>
  (async () => {
    const sdk = window.Glint ? await window.Glint.init() : null;
    const canvas = document.getElementById("unity-canvas");
    const maxDpr = Math.min(2, sdk ? sdk.system.getHints().maxDpr : (window.devicePixelRatio || 1));
    createUnityInstance(
      canvas,
      {
        dataUrl: "./Build/{{{ DATA_FILENAME }}}",
        frameworkUrl: "./Build/{{{ FRAMEWORK_FILENAME }}}",
        codeUrl: "./Build/{{{ CODE_FILENAME }}}",
        streamingAssetsUrl: "./StreamingAssets",
        companyName: "{{{ COMPANY_NAME }}}",
        productName: "{{{ PRODUCT_NAME }}}",
        productVersion: "{{{ PRODUCT_VERSION }}}",
        devicePixelRatio: maxDpr,
      },
      progress => {
        if (sdk) sdk.lifecycle.loadingProgress(Math.min(0.95, progress));
      },
    ).then(() => {
      if (sdk) sdk.lifecycle.ready();
    });
  })();
</script>
```

If your game needs more loading after Unity starts, such as downloading a first level, remove the `ready()` call from the template and call `Glint.Instance.Ready()` from C# when the first screen is interactive.

## Build Uncompressed

In **Project Settings > Player > Publishing Settings**, set **Compression Format** to **Disabled**. Glint compresses the `.wasm`, `.data` and `.js` files with Brotli when you upload, so there's no reason to do it twice. See [Uncompressed Export and Brotli Repackaging](https://joinfoundry.xyz/help/developers/glint-sdk-platform-rules#uncompressed-export-and-brotli-repackaging).

If you keep Brotli or Gzip, Glint serves Unity's `.br` and `.gz` files as stored, with the right `Content-Encoding`, and doesn't compress them again.

## Call the SDK From C#

```csharp
using GlintSdk;
using UnityEngine;

public class FoundryBoot : MonoBehaviour
{
    [System.Serializable]
    private class Progress { public int bestScore; }

    [System.Serializable]
    private class SaveResult { public string slot; public Progress data; }

    private Progress progress = new Progress();

    private void Start()
    {
        var glint = Glint.Instance;
        glint.OnSaveLoadedJson += json =>
        {
            var result = JsonUtility.FromJson<SaveResult>(json);
            if (result.data != null) progress = result.data;
        };
        glint.OnPause += reason => glint.SaveJson("main", JsonUtility.ToJson(progress));
        glint.OnMuteChanged += muted => Debug.Log("Muted: " + muted);

        glint.LoadSlot("main");
        glint.GameplayStart();
    }

    public void OnLevelComplete(int score)
    {
        progress.bestScore = Mathf.Max(progress.bestScore, score);
        Glint.Instance.UnlockAchievement("first_win");
        Glint.Instance.SubmitScore("high_score", score);
        Glint.Instance.SaveJson("main", JsonUtility.ToJson(progress));
    }
}
```

The component already handles pause and mute:

- On pause it sets `Time.timeScale = 0` and `AudioListener.pause = true`. On resume it sets `Time.timeScale = 1` and restores audio unless Glint is muted.
- On master mute changes it sets `AudioListener.pause` to match, and updates `IsMuted`.

### Methods

| Method | What it does |
| --- | --- |
| `ReportProgress(float progress)` | `sdk.lifecycle.loadingProgress()`, clamped to 0 to 1. |
| `Ready()` | `sdk.lifecycle.ready()`. |
| `GameplayStart()` | `sdk.lifecycle.gameplayStart()`. |
| `GameplayStop()` | `sdk.lifecycle.gameplayStop()`. |
| `SaveJson(string slot, string json)` | `sdk.saves.save()`. `json` must be valid JSON; the plugin ignores anything else. |
| `LoadSlot(string slot)` | `sdk.saves.load()`. The result arrives through `OnSaveLoadedJson`. |
| `UnlockAchievement(string key)` | `sdk.achievements.unlock()`. |
| `SubmitScore(string boardKey, double score)` | `sdk.leaderboards.submit()`. |
| `CreateRoom(string mode = "default", int maxPlayers = 8)` | `sdk.multiplayer.createRoom()`, then raises `OnRoomJoinedJson`. |
| `JoinRoom(string code, bool asSpectator = false)` | `sdk.multiplayer.joinRoom()`, then raises `OnRoomJoinedJson`. |
| `SendRoomMessage(string target, string type, string jsonPayload)` | `room.send()` with a JSON payload. `target` is `"all"`, `"others"`, `"host"` or a player ID. |
| `OpenInviteDialog()` | `sdk.multiplayer.openInviteDialog()`. |

### Events and Properties

| Member | Payload |
| --- | --- |
| `event Action<string> OnReady` | JSON: `{"player":{...},"muted":false,"pendingInviteCode":""}` |
| `event Action<string> OnPause` | The pause reason: `tab_hidden`, `host_overlay`, `demo` or `free-hours` |
| `event Action OnResume` | None |
| `event Action<bool> OnMuteChanged` | The new mute state |
| `event Action<string> OnSaveLoadedJson` | JSON: `{"slot":"main","data":...}`, with `data` set to `null` for an empty slot |
| `event Action<string> OnRoomJoinedJson` | JSON: `{"id":...,"code":...,"selfId":...,"hostId":...,"isHost":...}` |
| `event Action<string> OnRoomMessageJson` | JSON: `{"from":...,"type":...,"payload":...}` |
| `event Action<string> OnHostChangedJson` | JSON: `{"hostId":...,"isSelfHost":...}` |
| `bool IsMuted` | Glint's current master mute |
| `static Glint Instance` | The component |

`OnReady` can fire before your `Start()` runs. Subscribe to it in `Awake()`, as the next example does, or skip it and read `IsMuted` and call `LoadSlot()` from `Start()`, as the example above does.

## Multiplayer From Unity

Set `multiplayer.online.enabled` to `true` in `glint.json`. The `pendingInviteCode` in `OnReady` holds the room code from an invite link:

```csharp
using GlintSdk;
using UnityEngine;

public class FoundryRooms : MonoBehaviour
{
    [System.Serializable]
    private class ReadyInfo { public string pendingInviteCode; }

    [System.Serializable]
    private class HostInfo { public string hostId; public bool isSelfHost; }

    private void Awake()
    {
        var glint = GetComponent<Glint>();
        glint.OnReady += json =>
        {
            var info = JsonUtility.FromJson<ReadyInfo>(json);
            if (!string.IsNullOrEmpty(info.pendingInviteCode)) glint.JoinRoom(info.pendingInviteCode);
            else glint.CreateRoom("arena", 4);
        };
        glint.OnHostChangedJson += json =>
        {
            var host = JsonUtility.FromJson<HostInfo>(json);
            if (host.isSelfHost) Debug.Log("This player now runs the match");
        };
        glint.OnRoomMessageJson += json => Debug.Log("Room message: " + json);
    }

    public void SendInput(bool jump)
    {
        Glint.Instance.SendRoomMessage("host", "input", jump ? "{\"jump\":true}" : "{\"jump\":false}");
    }
}
```

Put this script on the same GameObject as the Glint component, so its `Awake()` can subscribe before `OnReady` fires.

The plugin covers the calls above. For anything else, such as `quickJoin`, room state or binary frames, it keeps the SDK in `window.__fpUnitySdk` and the current room in `window.__fpUnityRoom`, so your own `.jslib` functions can call the rest of the [JavaScript API](https://joinfoundry.xyz/help/developers/glint-sdk-api).

## Preview, Validate and Zip

Build for WebGL into a folder, then:

```bash
glint preview path/to/build
glint validate path/to/build
```

Check that `index.html`, `glint.js` and `glint.json` are at the top of the build folder, then zip its contents with standard ZIP compression and upload it in Glint Studio. See [Upload a Build](https://joinfoundry.xyz/help/glint/upload-a-build).

## Size and Threads

- Unity's `.wasm`, `.data` and framework files count toward the initial boot payload, which has a 30 MB hard cap ([GL006](https://joinfoundry.xyz/help/developers/glint-sdk-cli#gl006)). Setting **Managed Stripping Level** to **High** removes unused managed code. Load extra content after `ready()`.
- Leave WebAssembly multithreading off. If your game needs it, set `"capabilities": { "threads": true }` in `glint.json`, and Glint runs it in [advanced mode](https://joinfoundry.xyz/help/developers/glint-sdk-platform-rules#advanced-mode-for-threads).
