# Unity integration

Extract this folder into `Packages/com.animstream.originals` or use Unity Package
Manager → Add package from disk → `package.json`. The package declares Unity's
Newtonsoft JSON package dependency. Import the Community Counter sample.

Attach one `AnimStreamGameClient` and `CommunityCounter` to a root GameObject in
your bootstrap scene. Keep that GameObject alive across scene changes using your
bootstrap's `DontDestroyOnLoad(gameObject)`. Register actions in `Awake`, before
the client's `Start` connects. Subscribe to `Ready` and gate game input on
`IsReady`; the example plays a 15-second lobby and 60-second rounds with the
`spawn`, `double-points`, `steal-points`, `shake-screen` and `GIFT` entries of
`manifest.example.json` (the shared manifest example: actions with descriptions
and images, three presets, `defaultBindings`, `giftWall`, `leaderboard`).

```csharp
// "spawn" is stackable in the manifest: Studio may merge a Rose x99 streak into ONE
// action with count 99 (older Studio sends 99 actions). Apply the whole count at once.
client.RegisterAction("spawn", (parameters, context) => {
    context.Cancellation.ThrowIfCancellationRequested();
    var count = (int?)parameters["count"] ?? 1;
    score += count;
    ShowToast($"+{count} ({(int?)context.Source["giftCount"] ?? 1} gifts)");
    client.SetState(true, "playing", score);
    return Task.CompletedTask;
});
client.Subscribe("GIFT", gift => ShowViewerText((string)gift["user"])); // ticker only
```

Callbacks enter on Unity's main thread and normal `await` continuations use
Unity's synchronization context. Do not use `ConfigureAwait(false)` before
Unity API calls. Honor cancellation before further effects; an already-applied
effect cannot be automatically undone. Throwing rejects the action with a safe
error code. Dry runs validate but do not call handlers. Async cancellation and
expiration return one result; late completion cannot replay the action. Studio
sends the next action only after the previous result, so start long effects and
return instead of awaiting them to the end.

`Application.runInBackground` is enabled so minimizing the game does not stop
heartbeats. Lost heartbeat, lease expiry, invalid identity, disconnect or Studio
stop cancels pending actions and calls `Application.Quit()` by default. Unity's
editor does not exit on `Application.Quit`, so observe `Stopped` and disable all
input there. A closed session is never automatically reconnected or replayed.

## Optional Studio features

Newer Studio versions announce capabilities in `ready`. After `Ready`, `Features`
lists them and `HasFeature("state")` checks one. `Language` (`"de"`/`"en"`) and
`StreamerHandle` (TikTok username without `@`, only if the streamer allowed
sharing it; display data only) are null when absent. Studio 0.1.285 and older
announce nothing: the client then never sends `state` or `request` frames (old
Studio would end the session) and the calls below fail locally, so the game must
also work without them. Call them on the main thread.

- `GameActionContext.Source` (feature `source`): `code`, `giftId`, `giftName`,
  `giftCoins`, `giftCount` (gifts a stacked action represents); empty if absent.
- `bool SetState(bool acceptingActions, string phase, double? score = null)`
  (feature `state`): while `acceptingActions` is false Studio holds new actions
  (menus, round breaks, cutscenes). Phase matches `^[a-z0-9][a-z0-9-]{0,31}$`,
  `|score| <= 1e15`; invalid input is logged with `Debug.LogError` and ignored.
  Identical states are sent once and changes are coalesced to at most 10 per
  second, so call it as often as you like. A state set before `Ready` is sent
  once ready. Returns false if invalid or unsupported.
- `Task<GameRequestResult> SubmitScore(long score)`, `GetLeaderboard(int limit = 10)`,
  `ListBindings()` and the generic `Request(string op, JObject parameters = null)`
  (features `leaderboard`, `bindings`). Results have `Ok`, `Data` (`JObject`,
  never null) and `Error`; tasks never fault and continue on the main thread.
  Local errors complete on the next frame without sending anything:
  `unsupported`, `not_ready`, `invalid`, `busy` (4 requests in flight), plus
  `timeout` (15 s) and `stopped` (session ended). Studio may answer
  `rate_limited` (one submission per 2 s), `unavailable` (offline or signed out),
  `busy`, `invalid` or `unsupported`.
- `event Action BindingsChanged`: after a successful `ListBindings`, Studio
  reports changed gift rules; call `ListBindings` again to refresh a legend.

```csharp
private async void EndRound()
{
    client.SetState(false, "round-over", score); // Studio holds new actions meanwhile.
    var result = await client.SubmitScore(score);
    if (result.Ok) ShowBest((long)result.Data["best"]); // Data: best, rank (or null), improved
    else Debug.Log("Leaderboard: " + result.Error);     // "unsupported" on older Studio, ...
}
```

Every published game has a global leaderboard (best score per streamer); submit
the final score of a round or run as an integer from 0 to 10^12. Durations are
integer milliseconds with `"order": "asc"` in the manifest.

### Leaderboard pictures (feature `leaderboard-avatars`)

`GetLeaderboard` entries and `self` carry `avatarUrl`: a 128×128 PNG on
AnimStream's CDN, or null (anonymous, not shared by the streamer, hidden by
moderation, invalid, or an older Studio). The client already replaces invalid
values with null; `AnimStreamGameClient.IsAvatarUrl(url)` applies the same rule.
URLs need no cookies or Referer and never change content, so cache textures by
URL. Load them in the background and keep the initial as fallback for null,
404, timeouts and broken images:

```csharp
// using UnityEngine.Networking;
private IEnumerator LoadAvatar(string url, RawImage target, Text initial)
{
    if (!AnimStreamGameClient.IsAvatarUrl(url)) yield break; // keep the initial
    using (var request = UnityWebRequestTexture.GetTexture(url))
    {
        request.timeout = 5; // seconds
        request.redirectLimit = 0;
        yield return request.SendWebRequest();
        if (request.result != UnityWebRequest.Result.Success || request.downloadedBytes > 1024 * 1024) yield break;
        var texture = DownloadHandlerTexture.GetContent(request);
        if (texture == null || texture.width > 1024 || texture.height > 1024) yield break;
        target.texture = texture; target.enabled = true; initial.enabled = false;
    }
}
```

Never delay a round or the round-over screen for a picture.

## Gift rules and the game control window

Streamers map TikTok gifts to your manifest actions in Studio's **game control
window** (DE "Spielsteuerung", EN "Game control"). It opens beside the game when
the game connects; F7 brings it above a fullscreen game. Do not bind F7, prefer
windowed or borderless fullscreen (exclusive fullscreen can hide Studio
windows), and build no gift mapping UI of your own. `defaultBindings` in the
manifest suggests first rules; the streamer confirms them.

Avoid double triggering: if the manifest lists `GIFT` in `events`, one gift can
arrive both as a raw event and as an action from a gift rule. Apply gameplay
only in action handlers; use `Subscribe("GIFT", ...)` for tickers and ambient
reactions.

## Originals checklist in Unity

Every AnimStream Original meets the binding checklist of the agent kit
(`AGENTS.md`, "Originals checklist (binding)"). The Godot template is its
reference implementation; Unity has no template, so build the same behavior with
this guidance (details in the kit skill `animstream-game`, `engines/unity.md`):

- **Manifest** (points 1–6): copy `manifest.example.json`; every action with
  de/en label, description ≤ 120 characters and `media/actions/<id>.png`
  (art direction and generator: agent kit `ART-DIRECTION.md` and
  `tools/art/generate-action-images.mjs`; glossy 3D cartoon clipart,
  transparent, square 512×512, ≤ 300 KB); three
  presets by coin value (≤ 30, 99–299, ≥ 500 coins) mixing sabotage and mercy;
  `defaultBindings` = the cheap preset; `giftWall` with `sort: "preset"`.
- **Lobby** (7): on `Ready` call `SetState(true, "lobby")`, keep actions that
  arrive and apply them in round 1, start round 1 after ~15 s without a key.
- **Language** (8): `client.Language`, else `Application.systemLanguage`;
  switchable in the lobby and the pause menu; saved with `PlayerPrefs`.
- **Pause** (9): Esc opens a menu (controls, language, music and effects volume,
  mute, saved in `PlayerPrefs`); `SetState(false, "paused")`,
  `Time.timeScale = 0` for gameplay; the client keeps its heartbeat (it uses its
  own clock in `Update`), so never disable its GameObject.
- **Leaderboard** (10): `SubmitScore`, then `GetLeaderboard` on the round-over
  screen with `self` highlighted and pictures as shown above.
- **Window** (11): windowed at most ~1080×1180; F11 toggles
  `FullScreenMode.FullScreenWindow` (borderless), never `ExclusiveFullScreen`;
  never bind F7.
- **Audio** (12): an `AudioMixer` with music and effects groups; several
  licensed tracks played shuffled (licence covering live streaming and selling
  the game).
- **Tests** (14): the kit's mock Studio scenarios `smoke`, `stacking`, `pause`,
  `leaderboard`, `smoke --legacy`, `presets` and `lobby` against the built
  player.

## Export

Export a standalone native Windows/Linux/macOS player with its data folder,
not WebGL. Use .NET Standard 2.1 or an equivalent profile supporting
`System.Net.WebSockets.ClientWebSocket`, and verify the chosen scripting backend
on each target. See `PROTOCOL.md` (included in this download) for the messages
and manifest, and `ANIMSTREAM-SDK.md` for packaging and review requirements.
