# Bitey Games SDK — Unity (WebGL) Developer Guide (v1.3)

> **Update (Nov 2026):** If you copied the kit into your game (e.g. `src/vendor/biteygames-sdk/index.mjs`),
> the app now works without changes, but please replace that file with the latest
> [`biteygames-sdk.mjs`](https://biteygames.com/downloads/biteygames-sdk.mjs) so you get future fixes.
> New games: nothing extra for the app — call `connect({ gameKey })`, start a session, use wallet/save/score
> through the kit, and call shut-down on Exit.


Downloads: Developer Dashboard → Docs → Unity (`BiteyGames-Unity.unitypackage` or UPM .zip).

**New in v1.3:** games recognise the player inside the Bitey Games mobile app. If you use the BiteyGames WebGL template, nothing to change. Make sure your Exit button calls `BiteyGames.Instance.Shutdown()`.


Unity games run on Bitey Games as **WebGL builds**. This package connects your game to the platform with plain C#. You don't need to write any JavaScript.

Requires Unity 2021.3 or newer, with the WebGL Build Support module installed.

## Setup
1. Import the package. Double-click `BiteyGames-Unity.unitypackage`, or add `packages/unity` through Package Manager → "Add package from disk".
2. Copy `WebGLTemplates/BiteyGames` into your project's `Assets/WebGLTemplates/`. (The `.unitypackage` already places it there.)
3. In your first scene, create an empty GameObject named **BiteyGames** and add the `BiteyGames` component. Then set your **Game Key** (`gk_...`) from the Developer Dashboard.
4. Open Player Settings → WebGL → Resolution and Presentation, and pick the **BiteyGames** template.
5. Build for WebGL. Upload the build folder, or host it and paste the link, in Developer Dashboard → your game.

When the game runs inside the Unity Editor, the package works in **mock mode** and returns sample data. To test a WebGL build on localhost, paste a dev token (`bdt_...`) into **Dev Token**. Leave it empty in production builds.

## Usage
```csharp
using BiteyGamesSDK;

var bg = BiteyGames.Instance;
bg.OnReady += hs => Debug.Log("Hi " + hs.user.username);

var session = await bg.StartSession();          // charges the entry fee if any
var save = await bg.LoadState<MySave>();         // your own [Serializable] class
save.level = 12;
await bg.SaveState(save);

await bg.AwardCoins(100, "run_complete");
var wallet = await bg.GetBalance();             // wallet.balance, wallet.bites_balance
var result = await bg.SubmitScore(4200);         // tournament id picked up automatically
var top = await bg.GetLeaderboard("weekly", 10);
await bg.TrackEvent("boss_defeated", 1);
await bg.EndSession();
```

Errors are thrown as `BiteyGamesException` with a `Code`, for example `INSUFFICIENT_FUNDS` or `STATE_CONFLICT`.

Events: `OnReady`, `OnPaused`, `OnResumed`, `OnSessionEnded`, `OnStateReloaded(json)`.

Advanced: `CallRaw(op, payloadJson)` calls any gateway operation directly. `Shutdown()` saves progress, then ends the session.

## Under the hood

The package is a thin bridge over the JavaScript SDK served at `https://biteygames.com/sdk`. All calls use the same gateway, operations and error codes as the HTML5 SDK, so the operations table and error codes in the HTML5 guide apply to Unity too.

## Update (Oct 2026): tournament scores
- Call score submit at the end of every round. Passing the tournament id is recommended, but no longer required: if it is missing, the score is credited to the player's live tournament for this game.
- Only scores sent between a tournament's start and end count; the player's highest score is kept.
- Game leaderboards (daily, weekly, monthly, all-time) are now built from saved scores and update within about 15 seconds.

## Update (Oct 30 2026): browsing without sign-in + "game not connected" checklist

### Public browse endpoints (no token needed)
These now work with **no** `Authorization` header, so the app can show content before sign-in:
`GET /home`, `/games`, `/games/:gameId`, `/genres`, `/upcoming`, `/tournaments`, `/tournaments/recommended`, `/tournaments/:id`, `/tournaments/:id/standings`.
If a token is sent, personal fields (wallet, missions, joined, recommendations) are filled in. Without one, `/home` returns `signed_in: false` with featured games, and tournaments return `is_guest: true`, `joined: false`.
Everything else (launch, play, wallet, missions, rewards, join, profile) still needs a token. To let users play straight away, the app can call `POST /auth/guest` silently on first launch.

### `:id` in `POST /games/:id/launch`
`:id` is the game's `id` from `GET /games` (e.g. Galactic Dash = `99c352b1-b6e3-4ae1-a3bf-364f4f808a70`).

### Game not spending/earning coins or losing purchases — check these
1. **The game must call the kit.** Spending: `await gv.wallet.debit(amount, "warship")`. Earning: `await gv.wallet.credit(amount, "run_reward")`. Keeping items: `gv.state.set({ ships: [...] })` then `await gv.state.save()` (load it back with `await gv.state.load()` on start). Items held only in game memory are lost on exit.
2. **The app must open `launch_url`**, not `play_url`. `launch_url` carries the player identity.
3. **Use the current kit.** Load it from `https://biteygames.com/sdk` or rebuild a bundled copy with the latest version.
4. **On Exit:** `await gv.shutdown()` (it saves state and ends the session) — and wait for it before the app closes the WebView. The app should close on the `gv:exit` message, not immediately on tap.
5. **Look at the browser console.** `[BiteyGames] NOT CONNECTED` means no identity reached the game (see item 2/3).

Quick test: play once in the app, buy something and finish a run, then check the player's wallet history — it should show one spend and one reward line for the game.

## Update (Nov 9 2026): fit the player's screen
Inside the mobile app the game fills the phone's screen in portrait or landscape. Make sure your game:
- sizes itself from the window (`window.innerWidth/innerHeight` plus a `resize` listener) instead of a fixed pixel width
- for Unity WebGL, uses the Bitey Games template and a Canvas Scaler set to "Scale With Screen Size"

A fixed-width game spills off the right side of the screen on phones.
