From c2a608632e4809334a6dffc112190d87c052f006 Mon Sep 17 00:00:00 2001 From: "pre-shared-workflows-auth[bot]" <168739156+pre-shared-workflows-auth[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 20:24:17 +0000 Subject: [PATCH] chore: publish 3 skills (build-live-game, build-multiplayer-game, setup-multiplayer-services) --- skills/build-live-game/SECURITY.md | 26 +- skills/build-live-game/SKILL.md | 79 ++-- .../references/achievements.md | 28 +- skills/build-live-game/references/apis.md | 7 +- .../references/authentication.md | 48 ++- .../build-live-game/references/battlepass.md | 22 +- .../references/blueprints-and-samples.md | 1 + .../references/cloud-code-cloudbehaviours.md | 128 ++++-- .../references/cloud-code-modules.md | 136 +++++-- .../build-live-game/references/deployment.md | 50 +-- .../build-live-game/references/link-cloud.md | 13 +- .../references/player-account.md | 26 +- .../references/remote-config.md | 6 +- skills/build-live-game/references/tooling.md | 2 +- skills/build-live-game/references/ugs-cli.md | 6 +- skills/build-multiplayer-game/SECURITY.md | 26 ++ skills/build-multiplayer-game/SKILL.md | 216 ++++++++++ .../references/architecture.md | 171 ++++++++ .../references/choosing-netcode.md | 44 ++ .../references/dgs-entrypoint.md | 46 +-- .../references/entrypoints.md | 20 + .../references/examples.md | 10 +- .../references/ghost-authoring.md | 19 + .../references/implementation-fit.md | 28 ++ .../references/link-cloud.md | 12 + .../references/multiplayer-play-mode.md | 245 +++++++++++ .../references/netcode-for-entities.md | 22 + .../references/netcode-lifecycle.md | 383 ++++++++++++++++++ .../references/performance-and-scale.md | 215 ++++++++++ .../references/session-connectors.md | 131 ++++++ .../references/syncing-gameplay.md | 316 +++++++++++++++ .../references/underlying-services.md | 4 +- .../references/verification-gate.md | 185 +++++++++ .../references/workflows-prerequisites.md | 8 +- skills/setup-multiplayer-services/SECURITY.md | 17 - skills/setup-multiplayer-services/SKILL.md | 84 ---- .../references/entrypoints.md | 213 ---------- .../references/implementation-fit.md | 32 -- 38 files changed, 2437 insertions(+), 588 deletions(-) create mode 100644 skills/build-multiplayer-game/SECURITY.md create mode 100644 skills/build-multiplayer-game/SKILL.md create mode 100644 skills/build-multiplayer-game/references/architecture.md create mode 100644 skills/build-multiplayer-game/references/choosing-netcode.md rename skills/{setup-multiplayer-services => build-multiplayer-game}/references/dgs-entrypoint.md (56%) create mode 100644 skills/build-multiplayer-game/references/entrypoints.md rename skills/{setup-multiplayer-services => build-multiplayer-game}/references/examples.md (80%) create mode 100644 skills/build-multiplayer-game/references/ghost-authoring.md create mode 100644 skills/build-multiplayer-game/references/implementation-fit.md create mode 100644 skills/build-multiplayer-game/references/link-cloud.md create mode 100644 skills/build-multiplayer-game/references/multiplayer-play-mode.md create mode 100644 skills/build-multiplayer-game/references/netcode-for-entities.md create mode 100644 skills/build-multiplayer-game/references/netcode-lifecycle.md create mode 100644 skills/build-multiplayer-game/references/performance-and-scale.md create mode 100644 skills/build-multiplayer-game/references/session-connectors.md create mode 100644 skills/build-multiplayer-game/references/syncing-gameplay.md rename skills/{setup-multiplayer-services => build-multiplayer-game}/references/underlying-services.md (90%) create mode 100644 skills/build-multiplayer-game/references/verification-gate.md rename skills/{setup-multiplayer-services => build-multiplayer-game}/references/workflows-prerequisites.md (71%) delete mode 100644 skills/setup-multiplayer-services/SECURITY.md delete mode 100644 skills/setup-multiplayer-services/SKILL.md delete mode 100644 skills/setup-multiplayer-services/references/entrypoints.md delete mode 100644 skills/setup-multiplayer-services/references/implementation-fit.md diff --git a/skills/build-live-game/SECURITY.md b/skills/build-live-game/SECURITY.md index 8316537..6e70d13 100644 --- a/skills/build-live-game/SECURITY.md +++ b/skills/build-live-game/SECURITY.md @@ -1,18 +1,30 @@ # Security notes: build-live-game -This skill has the agent read state from the user's open Unity Editor through `unity command script eval` to read the Cloud project ID after linking and the result of a feature it changed. Automated skill scanners flag that as a powerful capability. It is intentional, and it is limited by the safeguards below. +This skill has the agent change the user's Unity project and its Unity Gaming Services environment: it adds UGS packages, creates Cloud Code modules and cloud resource files, deploys them, and, when no named command covers a step, runs C# inside the user's open Unity Editor through `unity command script eval`. Automated skill scanners flag these as powerful capabilities. They are intentional, and limited by the safeguards below. ## Accepted risks | Risk | Capability | Why it is accepted | |---|---|---| -| `SEC_POWER_CAP` | Runs C# in the user's open Editor through `unity command script eval` | It only reaches the Editor the user already has open, on their own machine, as that user, so it grants nothing they couldn't do themselves. `script eval` sits behind the Pipeline capability gate. No code fetched from a remote source is run. The skill uses it only to read state, and uses `unity command console status` for the console check. | +| `SEC_POWER_CAP` | Runs C# in the user's open Editor through `unity command script eval`, and deploys cloud resources from the Editor to the project's linked UGS environment | It only reaches the Editor the user already has open, on their own machine, as that user, behind the Pipeline capability gate, and an Editor deploy goes only to the project and environment the project is linked to. Where a named `unity command` or `unity ugs` command covers a step, the skill uses that instead of `eval`. | +| `SEC_POWER_CAP` | Reads and writes live UGS data and deploys with the `unity ugs` CLI, which has its own credentials (a service account or Unity Hub sign-in) and its own target project and environment | It is outside the Editor and the Pipeline gate, so the skill has the agent check the CLI's configured project ID and environment against the linked project and the environment the user asked for before any write, and stop and ask if they differ. The credentials are the user's own. | +| `SEC_POWER_CAP` | Imports Unity's Asset Store Building Blocks and sample projects, whose runtime code and legacy Cloud Code (`.ccmr` modules, JavaScript scripts) then compile, deploy and run | These are Unity's own published packages, imported only when the user's feature matches one. The agent reviews the imported Cloud Code before deploying it, and the final report names every package it imported. | + +## What it changes + +- **Packages:** adds or upgrades UGS packages in `Packages/manifest.json`: `com.unity.services.core`, `com.unity.services.authentication`, `com.unity.services.cloudcode`, `com.unity.services.cloudsave`, `com.unity.remote-config`, `com.unity.services.leaderboards`, `com.unity.services.deployment`, `com.unity.services.tooling` and `com.unity.services.apis`, only those the feature needs, and `com.unity.pipeline` with `unity pipeline install` when linking the project needs it. +- **Project files:** creates scripts, Cloud Code modules (`.ccmu`, `.ccmr`) and cloud resource files (`.rc`, `.ac`, `.lb`, `.ugo`). +- **Project settings:** links the project to a Unity project ID and environment, after asking the user, and sets the API Compatibility Level a Cloud Code module needs. +- **Cloud environment:** deploys those resources to the active UGS environment, which changes the live configuration, Cloud Code and access policies that environment's players see. +- **CLI plugin:** installs the `unity ugs` plugin with `unity plugin install ugs` when it is missing, and sets its target project and environment. +- **Imported packages:** imports Asset Store Building Blocks or sample projects when the feature matches one. ## Mitigations -- **Only the user's own Editor.** `unity command script eval` talks to the Editor open on this machine. It can't reach another machine or another user's Editor. -- **Capability gate.** `script eval` is only available when the project's Pipeline package provides it. -- **No remote code.** The agent runs C# it writes itself to read Editor state. Nothing downloaded from outside is executed. -- **Reads, not logging.** `script eval` only reads state; the skill reads results with it instead of adding logging. The one write it makes for verification is a temporary client Cloud Save call that checks an Access Control policy rejects it, removed afterwards. -- **Play mode only when needed.** The skill enters Play mode for that Access Control check and, when the user asks for proof or a fault is suspected, once to run the feature. +- **Restore point first.** The skill requires a commit or a copy of the project before it changes anything. +- **Only the user's own Editor and linked project.** Everything runs on this machine as this user, against the environment the project is linked to. +- **No arbitrary remote code.** The agent runs C# it writes for the user's task. The only downloaded code is Unity's own Building Blocks and samples, imported when the feature matches one. +- **CLI target checked first.** Before a `unity ugs` write, the agent confirms the CLI's project ID and environment match the linked project and the requested environment. +- **Named commands first.** When a `unity command` or `unity ugs` command covers a step, the skill uses it instead of `eval`. - **One Editor.** Every `unity command` names the project with `--project-path`, so it can't drive another project's Editor. +- **Temporary checks are removed.** A temporary call added to test an Access Control policy is removed afterwards, and the final report lists it. diff --git a/skills/build-live-game/SKILL.md b/skills/build-live-game/SKILL.md index 56ffe66..6e2d442 100644 --- a/skills/build-live-game/SKILL.md +++ b/skills/build-live-game/SKILL.md @@ -1,6 +1,6 @@ --- name: build-live-game -description: Builds and operates a live game's backend with Unity Gaming Services. Make sure to use this skill when the user wants trusted server-side game logic, player progress, remote configuration, sign-in, achievements, battle passes or leaderboards. +description: Builds and operates a live game backend on Unity Gaming Services. Make sure to use this skill when the user wants sign-in or sign-in checks, trusted server-side game logic, player progress, remote config, achievements, battle passes or leaderboards. --- # Build a Live Game With Unity Gaming Services @@ -9,7 +9,7 @@ description: Builds and operates a live game's backend with Unity Gaming Service 1. Read the Editor version from `ProjectSettings/ProjectVersion.txt` and the installed UGS package versions from `Packages/packages-lock.json`. Pick the steps below that match (for example `.ccmu` or `.ccmr` modules), because the right workflow depends on the Editor and package versions. 2. Create a restore point you can roll back to if your changes fail: commit the project in version control. If there is no version control, copy the project folder instead. Do this before linking or any other write. -3. If the project has no Unity Cloud link, see [Link the Project to Unity Cloud](#link-the-project-to-unity-cloud). Advice-only questions stay read-only: give the `unity projects link cloud` command. +3. If the project has no Unity Cloud link and the task needs service calls or asks to link, follow [references/link-cloud.md](references/link-cloud.md), because linking writes project settings. Advice-only questions stay read-only: give the `unity projects link cloud` command. 4. Before you go forward with a workflow or diagnosis, open and read the documentation pages for the service you will use (see [Documentation Map](#documentation-map)) and the matching file under `references/`, and name the pages you read in your response. This is because your training knowledge about Unity Gaming Services might be out of date, incorrect, or for the wrong package version. 5. Do only what's asked. Don't change unrelated assets or files. Avoid long explanations. 6. Never leave verification code in the user's script. Never build logging or detection they didn't ask for. @@ -58,22 +58,6 @@ Pages to read before acting: | `com.unity.services.tooling` | 1.4.1 | Access Control and Game Overrides | | `com.unity.services.apis` | 1.1.1 | Generated REST clients for all UGS services | -- [Before You Start](#before-you-start) -- [Glossary](#glossary) -- [Documentation Map](#documentation-map) -- [Link the Project to Unity Cloud](#link-the-project-to-unity-cloud) -- [Initialization Pattern](#initialization-pattern) -- [Architecture — How Packages Combine](#architecture--how-packages-combine) -- [Core Services — Quick Reference](#core-services--quick-reference) -- [Common Architecture Patterns](#common-architecture-patterns) -- [Validation](#validation) -- [Detailed References](#detailed-references) -- [Final Report](#final-report) - -## Link the Project to Unity Cloud - -Service calls need a linked Cloud project. Link only when the task needs service calls or asks to link, and only after the restore point. Follow every step in [references/link-cloud.md](references/link-cloud.md): choose backend and COPPA setting, check the Pipeline package, close the Editor, link, reopen, verify. - ## Initialization Pattern Every UGS game starts the same way. `com.unity.services.core` must initialize first, then the player signs in: @@ -89,33 +73,7 @@ await AuthenticationService.Instance.SignInAnonymouslyAsync(); ## Architecture — How Packages Combine -``` - UnityServices.InitializeAsync() - │ - ▼ - AuthenticationService - (sign in → PlayerId) - │ - ┌───────────────┼───────────────┐ - ▼ ▼ ▼ - Remote Config Cloud Save Multiplayer - (game config, (player state, (sessions, - definitions, progress, matchmaking, - feature flags) preferences) lobbies) - │ │ - └───────┬───────┘ - ▼ - Cloud Code - (server-authoritative - writes, validation, - anti-cheat logic) - │ - ┌───────┴───────┐ - ▼ ▼ - Cloud Save Leaderboards - (Protected (score - writes) submission) -``` +`UnityServices.InitializeAsync()` runs first, then Authentication signs the player in and sets `PlayerId`. Remote Config (game definitions, feature flags), Cloud Save (player state) and Multiplayer (sessions, matchmaking) follow. Cloud Code reads Remote Config and Cloud Save and makes the server-authoritative writes: Protected Cloud Save data and leaderboard scores. **Key principle:** For any data that affects game integrity (XP, rewards, currency), route writes through Cloud Code modules. Direct client writes are only appropriate for non-sensitive data (preferences, display settings). @@ -128,12 +86,13 @@ await AuthenticationService.Instance.SignInAnonymouslyAsync(); Handles player identity; [How Authentication works](https://docs.unity.com/en-us/authentication/how-authentication-works.md) covers the sign-in methods. After sign-in `PlayerId` is available and the `SignedIn` event fires. `PlayerAccountService` (Unity browser sign-in) lives in a **separate assembly**: `Unity.Services.Authentication.PlayerAccounts`. - **Full reference:** [references/authentication.md](references/authentication.md) +- **Check state in Play mode** with the `services.authentication` CLI commands (`get_state`, `get_player_id`, `get_player_name`, `get_player_info`, ...), not `script eval`: [Inspect State from the CLI](references/authentication.md#inspect-state-from-the-cli) ### Cloud Code **Package:** `com.unity.services.cloudcode` **`3.0.0`** for native `.ccmu` authoring (Unity 6000.5+); `>= 2.10.3` maintains legacy `.ccmr` modules. Before you author a `.ccmu`, bump a manifest that pins `2.10.x` to `3.0.0` or later. -Runs server-side C# modules (.NET 8; .NET 10 on Unity 6.7+) for trusted operations. Check the project's Editor version, then **author new modules as `.ccmu` on Unity 6000.5+**: create the module inside the Unity project with **Create > Services > Cloud Code Module Script**. Unity compiles it with the project and generates its client bindings at compile time. `.ccmr` is legacy: on 6000.5+ maintain existing ones only; on an older Editor, author new modules as `.ccmr`. +Runs server-side C# modules (.NET 8; .NET 10 on Unity 6.7+) for trusted operations. Check the project's Editor version, then **author new modules as `.ccmu` on Unity 6000.5+**: create the module inside the Unity project with `unity command services.cloudcode create_module`, or the menu when the command is missing ([Create it](references/cloud-code-modules.md#create-it)). Unity compiles it with the project and generates its client bindings at compile time. `.ccmr` is legacy: on 6000.5+ maintain existing ones only; on an older Editor, author new modules as `.ccmr`. Call a `.ccmu` module from the client only through its generated bindings, never with `CallModuleEndpointAsync`. Use `CloudCodeService.Instance.CallModuleEndpointAsync` for legacy `.ccmr` modules only. Write new JavaScript scripts only when the user asks for them; maintain existing ones. @@ -158,7 +117,7 @@ Per-player key-value storage in three access classes (Default, Public, Protected ### Remote Config -**Package:** `com.unity.services.remote-config` (>= 4.2.5) +**Package:** `com.unity.remote-config` (>= 4.2.5) Server-side game configuration. Store game definitions (achievement lists, battle pass tiers, shop catalogs) as JSON entries updatable without a client build. Deployed via `.rc` files through the Deployment Window. @@ -196,6 +155,19 @@ Auto-generated REST clients for all UGS services, in four client types (`IGameCl - **Full reference:** [references/apis.md](references/apis.md) +## Choosing a Route + +Pick the route by what the step touches and whether an Editor is running: + +| The step | Route | +|---|---| +| Change the project (create a config file, module or component), or deploy it, with the Editor running | The `services.*` Pipeline commands. Find them with `unity command --query ` | +| Deploy, fetch or switch environments with no Editor running (CI, headless) | `unity ugs deploy`, `unity ugs fetch`, `unity ugs env`, for the file types the UGS CLI handles ([Headless Deploy by File Type](references/ugs-cli.md#headless-deploy-by-file-type)) | +| Read or change data on the live service: Cloud Save records, leaderboard scores, test players, deployed Cloud Code, access policies | `unity ugs` with the service's command: `cloud-save`, `leaderboards`, `player`, `cloud-code` or `access`. `unity ugs --help` lists what it can do | +| Deploy a `.ccmu` module or `.ugo` Game Overrides | The Editor only: `unity command services.deployment deploy_items`. `unity ugs deploy` silently skips both | + +Use `script eval` only when neither route has a command for the step. If `unity ugs` is missing, install it with `unity plugin install ugs`; auth and project setup are in [references/ugs-cli.md](references/ugs-cli.md). + ## Common Architecture Patterns ### Pattern 1: Config + State + Server Writes @@ -228,10 +200,10 @@ After writing code for a live game feature, run these checks in order. If one fa 1. Check the project compiles: read the Editor console (or the Editor log) and confirm zero compile errors. 2. Check the initialization order in the code: search for `UnityServices.InitializeAsync()` and confirm it runs before the sign-in call, and that sign-in completes before any service call. 3. Check that sensitive writes (XP, rewards, currency) go through Cloud Code: search the client code for Cloud Save `SaveAsync` calls on those keys and move any you find into a module. Also confirm each Cloud Save read uses the access class of the bucket that was written to, because a mismatched class returns no data. -4. Deploy the cloud resource files the feature uses (`.rc`, `.ac`, `.ccmu` or `.ccmr`, `.lb`; skip the types it does not use) to the active environment with the `Deploy.cs` script in `references/deployment.md`, and read its output: every file must report `Success`. A file reported as `not a deployable item`, or with an `Error` status, has failed. If the project does not have both packages the script needs, `com.unity.pipeline` and `com.unity.services.deployment.api`, ask the user to deploy from the Deployment Window and report each file's status. +4. Deploy the cloud resource files the feature uses (`.rc`, `.ac`, `.ccmu` or `.ccmr`, `.lb`; skip the types it does not use) to the active environment: set it with `unity command services.environment set_active_by_name` if needed, run `unity command services.deployment deploy_items --paths `, then run `unity command services.deployment list_items` and confirm every file is listed. A file reported as `not a deployable item`, or with an `Error` status, has failed. 5. Check Access Control by its effect: if the feature deploys an `.ac` policy that denies direct player writes, enter Play mode, run one direct client Cloud Save write to a key the policy covers (a temporary `SaveAsync` call), and confirm it fails with a `403`. Remove the temporary call afterwards. Skip this step when the feature has no `.ac` file. -6. Check for zero console errors with `unity command console status`. Pass `--project-path ` to every `unity command` here, so it drives this project's Editor. Older Editors name it `console_status`: check with `unity commands --grep console`. -7. Stop after step 6 unless the user asked for proof or you suspect a specific fault, and report that the feature was not run. To chase that fault, enter Play mode once (`unity command editor.playmode start`), run the feature, read the result (player ID, module return value, config) through `unity command script eval`, not added logging, then repeat step 6. Remove any temporary code afterwards. Take no screenshots. +6. When you run a feature that two or more players share, such as a table, a turn order or a match, run each player in its own Multiplayer Play Mode instance, signed in as its own player, and follow the `build-multiplayer-game` skill's Multiplayer Play Mode reference to set them up. Do not stand in for a player by switching authentication profiles in one Editor, by calling the Cloud Code endpoints from a script, or with server-side bots, because none of those runs a second game client, so none shows what another player's client receives. +7. Confirm the project has zero console errors with `unity command console status`, passing `--project-path ` to every `unity command` so it drives this project's Editor. Stop there unless the user asked for proof or you suspect a specific fault, and report that the feature was not run. To chase a suspected fault, enter Play mode once, run the feature once, read state with `unity command script eval --code ''` instead of adding logging, repeat the console check, and take no screenshots. If the fix does not work, reread the matching documentation pages and `references/` file. ## Detailed References @@ -256,6 +228,7 @@ After writing code for a live game feature, run these checks in order. If one fa When the work is done, end your response with a short report: 1. What you created or changed: files, packages added to `Packages/manifest.json`, cloud resource files, and the Unity Cloud project you linked (its ID, and whether the link created it). -2. The checks from [Validation](#validation) that you ran and their results, including any you could not run and why. -3. Follow-ups only the user can do, for example: deploy the cloud resources to the target environment, link the project to a Unity project ID and environment, complete a stubbed integration (such as battle pass `PurchasePremium`), or restore from the restore point you created if they reject the changes. -4. Which documentation pages you read. +2. Side effects: anything you changed beyond the request, such as files, packages, settings or scenes, and any temporary call you added and removed, or "none". +3. The checks from [Validation](#validation) that you ran and their results, including any you could not run and why. +4. Follow-ups only the user can do, for example: deploy the cloud resources to the target environment, link the project to a Unity project ID and environment, complete a stubbed integration (such as battle pass `PurchasePremium`), or restore from the restore point you created if they reject the changes. +5. Which documentation pages you read. diff --git a/skills/build-live-game/references/achievements.md b/skills/build-live-game/references/achievements.md index 6528b71..a3cea5c 100644 --- a/skills/build-live-game/references/achievements.md +++ b/skills/build-live-game/references/achievements.md @@ -468,11 +468,17 @@ public class AchievementManager : MonoBehaviour The `AchievementModule` reads and writes to the **Protected** Cloud Save bucket using its service token, bypassing Access Control restrictions imposed on the player client. -> **Create the module with the Editor, not by hand.** Right-click a folder under `Assets/` -> -> **Create > Services > Cloud Code Module Script** and name it `AchievementModule`. See +> Create it with these commands: +> +> ```bash +> unity command services.cloudcode create_module --module-name AchievementModule --path Assets/CloudCode +> unity command services.cloudcode create_module_script --script-name AchievementModule --module-path Assets/CloudCode/AchievementModule/AchievementModule.ccmu +> ``` +> +> See > the Creating a Cloud Code Module section of `references/cloud-code-modules.md`. > -> The Editor generates the following. Use the list to check what you got — there is nothing here to +> The commands generate the following. Use the list to check what you got — there is nothing here to > type out, and no `.sln`, `.csproj`, `.pubxml` or test project: > > - [ ] `Assets/CloudCode/AchievementModule/AchievementModule.ccmu` (holds the two asmdef GUIDs) @@ -481,7 +487,7 @@ The `AchievementModule` reads and writes to the **Protected** Cloud Save bucket > - [ ] `Client/AchievementModuleClient.asmdef` — references the cloud assembly > - [ ] `Client/AchievementModuleClient.cs` — `[CloudModuleClient(typeof(AchievementModule))]` partial > -> One file the Editor does **not** generate, which this module needs because its endpoints inject +> One file the commands do **not** generate, which this module needs because its endpoints inject > `IGameApiClient`: > > - [ ] `Cloud/CloudSetup.cs` — an `ICloudCodeSetup` calling `config.AddGameApiClient()` @@ -678,7 +684,7 @@ Right-click in the Project window → **Assets > Create > Services > Remote Conf - `ProgressTarget > 1` means multi-stage (call `AddProgressAsync`). - `IsHidden = true` — show obfuscated title/description until unlocked. -Deploy via **Services > Deployment** — the Deployment Window auto-discovers `.rc` files under `Assets/`. +Deploy with `unity command services.deployment deploy_items --paths Assets/Config/Achievements.rc`. ### Cloud Code Module @@ -686,7 +692,7 @@ Deploy via **Services > Deployment** — the Deployment Window auto-discovers `. > See the Creating a Cloud Code Module section of `references/cloud-code-modules.md` > for the generic templates; replace `MyModule` with `AchievementModule`. > -> The `.ccmu` is deployed by the Deployment Window like any other cloud asset, but its code is compiled by +> The `.ccmu` is deployed like any other cloud asset, but its code is compiled by > Unity — a project that does not compile has nothing to deploy. ### Access Control -- `Assets/Config/DenyPlayerCloudSaveWrites.ac` @@ -715,21 +721,21 @@ Right-click in the Project window → **Assets > Create > Services > Access Cont **Without this policy:** `m_UseTrustedWrites = false` works fine — suitable for development or games where anti-cheat is not a concern. -Deploy via **Services > Deployment** alongside your other files. +Deploy it with `services.deployment deploy_items` alongside your other files. --- ## Deployment Checklist -Deploy all cloud resources via **Services > Deployment** before testing: +Deploy all cloud resources with `services.deployment deploy_items` before testing: - [ ] All packages added to `Packages/manifest.json` with correct minimum versions - [ ] `Assets/Config/Achievements.rc` -- Remote Config achievement definitions - [ ] `Assets/Config/DenyPlayerCloudSaveWrites.ac` -- Access Control policy blocking direct player writes - [ ] Cloud Code module authored as a `.ccmu`: module asset, `Cloud/` + `Client/` asmdefs, endpoint class, `CloudSetup.cs` (see file list in [Cloud Code Module](#cloud-code-module)) - [ ] `AchievementModule.cs` added to the module project with `UnlockAchievement`, `UpdateAchievementProgress`, `ResetAchievements` functions -- [ ] Environment selected in the Deployment Window dropdown -- [ ] All resources deployed via the Deployment Window +- [ ] Active environment set with `unity command services.environment set_active_by_name --name ` +- [ ] All resources deployed with `services.deployment deploy_items` - [ ] Project linked in **Edit > Project Settings > Services** --- @@ -754,4 +760,4 @@ After implementing achievements, verify: 5. **One record definition:** `AchievementRecord` is declared only in the Cloud Code module, as `{ get; set; }` properties, and the client uses the generated stub of that type. 6. **Access Control deployed:** The `.ac` file denies direct player writes to Cloud Save. Without this, the trusted-write path has no enforcement advantage. 7. **Remote Config key matches:** The `.rc` file key (`"achievements"`) matches the key used in `result.config["achievements"]` on the client and `AchievementsKey` in the module. -8. **All cloud resources deployable:** The `.rc`, `.ac`, and `.ccmu` files are in the `Assets/` folder hierarchy and appear in the Deployment Window. +8. **All cloud resources deployable:** The `.rc`, `.ac`, and `.ccmu` files are in the `Assets/` folder hierarchy and are listed by `unity command services.deployment list_items`. diff --git a/skills/build-live-game/references/apis.md b/skills/build-live-game/references/apis.md index b718f5a..ff94b20 100644 --- a/skills/build-live-game/references/apis.md +++ b/skills/build-live-game/references/apis.md @@ -73,7 +73,7 @@ var adminClient = ApiService.CreateAdminClient(); adminClient.SetServiceAccount(keyId, keySecret); ``` -Service account credentials are created in the Unity Dashboard under **Project Settings > Service Accounts**. The key ID and secret are passed at runtime — do not hard-code them. +Service account credentials are created in the Unity Dashboard under **Project Settings > Service Accounts**. The key ID and secret are passed at runtime — read them from environment variables or a secret store, never hard-code them or pass them as command-line arguments, because source ships in builds and arguments show in shell history and process listings. ### IAdminClient Service Area Properties @@ -199,8 +199,11 @@ Same service area properties as `IServerClient`, plus `PlayerAuthentication` and using Unity.Services.Apis; // Admin client is editor-only. Guard with #if UNITY_EDITOR in runtime assemblies. +// The same variables the UGS CLI reads; set them from the shell or CI secret store, never commit the values. var adminClient = ApiService.CreateAdminClient(); -adminClient.SetServiceAccount("your-key-id", "your-key-secret"); +adminClient.SetServiceAccount( + System.Environment.GetEnvironmentVariable("UGS_CLI_SERVICE_KEY_ID"), + System.Environment.GetEnvironmentVariable("UGS_CLI_SERVICE_SECRET_KEY")); ``` ### Write Game Data (Custom Data) from the Editor diff --git a/skills/build-live-game/references/authentication.md b/skills/build-live-game/references/authentication.md index 8736f8f..f831a78 100644 --- a/skills/build-live-game/references/authentication.md +++ b/skills/build-live-game/references/authentication.md @@ -5,6 +5,7 @@ - [Anti-Hallucination Reference](#anti-hallucination-reference) - [Sign-In Methods](#sign-in-methods) - [Key Properties](#key-properties) +- [Inspect State from the CLI](#inspect-state-from-the-cli) - [Events](#events) - [Player Info / Name](#player-info--name) - [Link / Unlink Methods](#link--unlink-methods) @@ -112,6 +113,37 @@ Task DeleteAccountAsync() --- +## Inspect State from the CLI + +Game code reads authentication state in C#. To check that state yourself while the game runs, use the `services.authentication` CLI commands. Never read `AuthenticationService.Instance` by evaluating C# with `script eval`. The commands return the same state without running code in the user's Editor. + +The following table lists each command and the property it returns. + +| Command | Returns | +|---|---| +| `get_state` | `SignedOut`, `SigningIn`, `Authorized`, `Refreshing`, or `Expired` | +| `get_signed_in` | `IsSignedIn` | +| `get_authorized` | `IsAuthorized` | +| `get_player_id` | `PlayerId` | +| `get_profile` | `Profile` | +| `get_access_token` | `AccessToken` (the raw JWT) | +| `get_player_name` | `PlayerName`. The game must call `GetPlayerNameAsync` first, otherwise it returns a cached name or nothing | +| `get_player_info` | `PlayerInfo`. The game must call `GetPlayerInfoAsync` first, otherwise it can lack the creation time, linked identities, and username | + +These are runtime commands, so they fail outside Play mode and before the services initialize. To run one: + +1. Read each command's arguments from `unity command --query services.authentication --format json`, because the arguments can differ between package versions. +2. Read the play state with `unity command editor status`. If its `playMode` reads `stopped`, enter Play mode with `unity command editor.playmode start`. Otherwise the session is the user's: inspect it and change nothing. +3. Wait until `unity command services.core get_initialization_state` returns `Initialized`. If it returns `Failed` or stays `Uninitialized`, stop and read the Console, because the game never initialized the services. +4. Run the command you need, for example `unity command services.authentication get_state`: + - `get_state`, `get_signed_in`, `get_authorized`, and `get_profile` work as soon as the services initialize. Report `SignedOut` or `SigningIn` as the player's state, not as an error. + - `get_player_id`, `get_access_token`, `get_player_name`, and `get_player_info` need a signed-in player. Run them only when `get_signed_in` returns `true`, otherwise they return an empty value. +5. If you entered Play mode in step 2, exit it with `unity command editor.playmode stop`. Never stop the user's session, because stopping it discards its runtime state. + +The Editor command `services.authentication add_player_authentication_component` adds a scene component that signs the player in without game code. Never add it when the game's own code already signs in, because the player would sign in twice. + +--- + ## Events | Event | Signature | When fired | @@ -195,7 +227,7 @@ void ClearSessionToken() void ProcessAuthenticationTokens(string accessToken, string sessionToken = default) ``` -Use `SwitchProfile(string profile)` before sign-in to store separate cached credentials per-profile (useful for multiple accounts on one device). Must be called BEFORE signing in -- call `SignOut()` first if already signed in. +Use `SwitchProfile(string profile)` before sign-in to store separate cached credentials per-profile (useful for multiple accounts on one device). Must be called BEFORE signing in -- call `SignOut()` first if already signed in. It is not a second player for testing a multiplayer feature: one game instance holds one signed-in player at a time, so test shared play with one Multiplayer Play Mode instance per player. --- @@ -261,10 +293,20 @@ Task UpdatePasswordAsync(string currentPassword, string newPassword) | Steam | Publisher Web API Key | Session ticket + identity | `SignInWithSteamAsync(sessionTicket, identity)` | | Oculus | App ID, App Secret | Nonce + user ID | `SignInWithOculusAsync(nonce, userId)` | | OpenID Connect | Client ID, Client Secret, Issuer URL | ID token | `SignInWithOpenIdConnectAsync(providerName, idToken)` | -| Unity Player Accounts | Enable in dashboard | Access token | `SignInWithUnityAsync(token)` | +| Unity Player Accounts | Turn on Player Accounts (`references/player-account.md`) | Access token | `SignInWithUnityAsync(token)` | | Username / Password | Enable in dashboard | Username + password | `SignInWithUsernamePasswordAsync(u, p)` | -All social identity providers are configured in the **Unity Dashboard**: Your project > Products > Authentication > Identity Providers > Add provider. +Identity providers are configured per project, outside the game code, and a sign-in method fails with `InvalidProvider` until its provider is configured. + +### Configure a Provider + +1. Check that the UGS CLI plugin runs: `unity ugs --version`. If it fails, install it with `unity plugin install ugs`. Do this first, because without the plugin the next check fails too, which would wrongly read as the commands being unavailable. + The `id-provider` commands need UGS CLI 2.1.0 or later. If the version is older, run `unity plugin upgrade ugs`. If it still reports an older version, the plugin registry does not offer 2.1.0 yet. Tell the user, and either use the Dashboard (step 5) or, if they agree, download the 2.1.0 build for their platform from the UGS CLI GitHub releases and put it on PATH as `ugs`: `unity ugs` runs a `ugs` on PATH ahead of the plugin's copy. +2. Whether or not you installed it, make sure the CLI is signed in and targets the user's project, as in Auth and Project Setup in `references/ugs-cli.md`. Compare `unity ugs config get project-id` with the project ID in **Edit > Project Settings > Services**, and set it with `unity ugs config set project-id` if they differ. The CLI keeps its own sign-in and project, separate from the Editor's link, so a stale one creates the provider in another project without an error. +3. Run `UGS_CLI_PREVIEW=player-id-providers unity ugs player id-provider --help`. The `id-provider` commands are a preview: the CLI hides them unless `UGS_CLI_PREVIEW` names `player-id-providers`, so prefix every `id-provider` command with it. In PowerShell, set `$env:UGS_CLI_PREVIEW = 'player-id-providers'` for the session instead. A preview can change between releases, so check `--help` before relying on the commands. +4. If it lists the commands, run `UGS_CLI_PREVIEW=player-id-providers unity ugs player id-provider list-types` to see the fields each provider type needs, then `UGS_CLI_PREVIEW=player-id-providers unity ugs player id-provider create --client-id `. Pipe a client secret in with `--client-secret-stdin`, never as an argument, because arguments are kept in shell history and process lists. Confirm the result with `UGS_CLI_PREVIEW=player-id-providers unity ugs player id-provider list`. +5. If it reports an unknown command, don't guess other command names. Ask the user to add the provider in the **Unity Dashboard**: Your project > Products > Authentication > Identity Providers > Add provider. +6. Don't create the Unity Player Accounts provider (`unity`) directly: turning on Unity Player Accounts creates it and points it at the project's Player Accounts client. Follow Turn On Unity Player Accounts in `references/player-account.md`. --- diff --git a/skills/build-live-game/references/battlepass.md b/skills/build-live-game/references/battlepass.md index 890a4dc..6bf98c9 100644 --- a/skills/build-live-game/references/battlepass.md +++ b/skills/build-live-game/references/battlepass.md @@ -518,11 +518,17 @@ public class BattlePassTester : MonoBehaviour ## Cloud Code Module Implementation -> **Create the module with the Editor, not by hand.** Right-click a folder under `Assets/` -> -> **Create > Services > Cloud Code Module Script** and name it `BattlePassModule`. See +> Create it with these commands: +> +> ```bash +> unity command services.cloudcode create_module --module-name BattlePassModule --path Assets/CloudCode +> unity command services.cloudcode create_module_script --script-name BattlePassModule --module-path Assets/CloudCode/BattlePassModule/BattlePassModule.ccmu +> ``` +> +> See > the Creating a Cloud Code Module section of `references/cloud-code-modules.md`. > -> The Editor generates the following. Use the list to check what you got — there is nothing here to +> The commands generate the following. Use the list to check what you got — there is nothing here to > type out, and no `.sln`, `.csproj`, `.pubxml` or test project: > > - [ ] `Assets/CloudCode/BattlePassModule/BattlePassModule.ccmu` (holds the two asmdef GUIDs) @@ -531,7 +537,7 @@ public class BattlePassTester : MonoBehaviour > - [ ] `Client/BattlePassModuleClient.asmdef` — references the cloud assembly > - [ ] `Client/BattlePassModuleClient.cs` — `[CloudModuleClient(typeof(BattlePassModule))]` partial > -> One file the Editor does **not** generate, which this module needs because its endpoints inject +> One file the commands do **not** generate, which this module needs because its endpoints inject > `IGameApiClient`: > > - [ ] `Cloud/CloudSetup.cs` — an `ICloudCodeSetup` calling `config.AddGameApiClient()` @@ -829,7 +835,7 @@ Place at `Assets/BattlePasses.rc`. Contains pass definitions as a JSON array und > See the Creating a Cloud Code Module section of `references/cloud-code-modules.md` > for the generic templates; replace `MyModule` with `BattlePassModule`. > -> The `.ccmu` is deployed by the Deployment Window like any other cloud asset, but its code is compiled by +> The `.ccmu` is deployed like any other cloud asset, but its code is compiled by > Unity — a project that does not compile has nothing to deploy. ### Access Control @@ -874,8 +880,8 @@ Ensure these packages are listed in `Packages/manifest.json`: - [ ] Remote Config `.rc` file created with `"battle_passes"` entry and at least one active pass - [ ] Cloud Code module authored as a `.ccmu`: module asset, `Cloud/` + `Client/` asmdefs, endpoint class, `CloudSetup.cs` (see file list in [Cloud Code Module Implementation](#cloud-code-module-implementation)) - [ ] `BattlePassModule.cs` added to the module project with `AwardXp`, `ClaimReward`, `PurchasePremium` functions -- [ ] Environment selected in **Services > Deployment** settings -- [ ] Deploy all via the Deployment Window: select `BattlePasses.rc` and `BattlePassModule.ccmu`, click **Deploy** +- [ ] Active environment set with `unity command services.environment set_active_by_name --name ` +- [ ] Deploy with `unity command services.deployment deploy_items --paths Assets/BattlePasses.rc,Assets/CloudCode/BattlePassModule/BattlePassModule.ccmu` - [ ] Project linked in **Edit > Project Settings > Services** --- @@ -892,7 +898,7 @@ After implementing the battle pass feature, verify: 6. **No direct client writes** to `"battle_pass_progress"` -- all mutations go through Cloud Code. 7. **No client-supplied tier data**: `AwardXp` and `ClaimReward` use the module's server-side `PassTiers`, which matches the `XpRequired` values in `BattlePasses.rc`, and reject passes outside the server-side `PassWindows` (matching `StartDate`/`EndDate`). 8. **Date filtering** uses `DateTime.UtcNow` with `DateTimeStyles.RoundtripKind` for consistent UTC parsing. -9. **Cloud resources** are present and deployable: `BattlePasses.rc` and `BattlePassModule.ccmu` appear in the Deployment Window. +9. **Cloud resources** are present and deployable: `BattlePasses.rc` and `BattlePassModule.ccmu` are listed by `unity command services.deployment list_items`. 10. **PurchasePremium is an integration stub** -- it returns existing progress when `HasPremium` is already true and otherwise throws until you add purchase validation. 11. **ClaimReward validates** the pass window (`PassWindows`), tier reach (against `PassTiers`) and premium ownership before recording the claim. 12. **Premium purchasing is not deployable until a validated purchase flow sets `HasPremium`** -- keep the fail-closed throw until then. diff --git a/skills/build-live-game/references/blueprints-and-samples.md b/skills/build-live-game/references/blueprints-and-samples.md index 2d11050..3df411a 100644 --- a/skills/build-live-game/references/blueprints-and-samples.md +++ b/skills/build-live-game/references/blueprints-and-samples.md @@ -25,6 +25,7 @@ The Building Blocks and sample projects predate native module authoring. Their C - On Unity 6000.5+, do not copy their solution scaffolding, `.ccmr` files or raw `CallModuleEndpointAsync` calls into new work. On an older Editor, which cannot author `.ccmu`, `.ccmr` is the supported path. - On Unity 6000.5+, to reuse a block's server logic, move each `[CloudCodeFunction]` class into a new `.ccmu` module and call it through the module's generated client. The Creating a Cloud Code Module and Migrating a `.ccmr` to `.ccmu` sections of `references/cloud-code-modules.md` cover both steps. - An imported block's `.ccmr` still deploys and runs. Maintain it as legacy until you port it, rather than rewriting it unasked. +- Read an imported block's Cloud Code before you deploy it, because it runs on the user's backend, and name every Building Block or sample you imported in the final report. --- diff --git a/skills/build-live-game/references/cloud-code-cloudbehaviours.md b/skills/build-live-game/references/cloud-code-cloudbehaviours.md index 19b91bc..92c49a8 100644 --- a/skills/build-live-game/references/cloud-code-cloudbehaviours.md +++ b/skills/build-live-game/references/cloud-code-cloudbehaviours.md @@ -30,14 +30,14 @@ synchronize, plain Cloud Code modules are generally available and the better def | Requirement | Detail | | :-- | :-- | -| `com.unity.services.cloudcode` **`3.1.0-exp.1`**+ | Confirm in the project with **Create > Services > Cloud Behaviour Script** in the create menu | +| `com.unity.services.cloudcode` **`3.1.0-exp.1`**+ | Confirm that `unity command --query create_cloudbehaviour` lists `services.cloudcode create_cloudbehaviour`, or that **Assets > Create > Services > Cloud Behaviour Script** exists | | Editor is 6000.5 or newer | every CloudBehaviours assembly is gated on `UNITY_6000_5_OR_NEWER` | | Project is linked to a Unity Cloud project | required to deploy, and to authenticate at runtime | `Scope.MultiplayerSession` additionally needs `com.unity.services.multiplayer` installed. Player-scoped behaviours do not. One module can hold CloudBehaviours and native Cloud Code classes side by side. -If the create-menu entry is missing, say so and do not write CloudBehaviour code: the installed version +If both the command and the menu item are missing, say so and do not write CloudBehaviour code: the installed version does not carry CloudBehaviours and no amount of correct code will compile against it. Fall back to a plain stateful module unless the user asks for the experimental package. @@ -61,20 +61,25 @@ stateful module unless the user asks for the experimental package. | client calls the generated method: `await behaviour.PlayTurn(move)` | `CallModuleEndpointAsync("Behaviour", "PlayTurn", args)` from a behaviour's client | | `Synchronized`, `ScopeChanged`, `Fatal`, `Error`, `MessageReceived` on the generated bindings | any other event name for connection or state callbacks | | read synchronized fields in a `ScopeChanged` handler -- the client hydrated before raising it | calling `Hydrate()` on connect or reconnect -- it already ran, and yours is a second RPC | +| let the generated clients pre-warm the module host -- they arm the shared `ModuleHostWarmup.Default` when the game loads and it runs at sign-in | trying to call the warm route yourself -- `ModuleHostWarmup` is the only public entry and the generated code already arms it. A host without the warm route is skipped silently; a warm-up that runs out of retries raises `Fatal` with `InvokerUnavailable` and the client is disabled before it hydrates, until `EnableClient()` asks for another warm-up | | `List`, `T[]`, `Dictionary<,>` across the boundary | a custom `IEnumerable` type -- compile-time error | | model types carrying only fields and properties | methods or constructors on a model -- not regenerated client-side; a computed or get-only property is error `CCSG131` | | behaviour class names unique within a module | two behaviours sharing a simple name across namespaces -- generator error | ## Creating the module -Always create a new module with **Create > Services > Cloud Behaviour Script**, because the creator writes -the module's `.ccmu` asset along with both assemblies, and the Deployment window lists only modules that -have a `.ccmu`. A module built from hand-written asmdefs alone compiles and generates bindings, but never -appears in the Deployment window, and nothing reports why. An agent without computer-use tools asks the -user to run this menu step; with them, it runs the step itself. +```bash +unity command services.cloudcode create_module --module-name MatchModule --path Assets/CloudCode +unity command services.cloudcode create_cloudbehaviour --behaviour-name MatchState --module-path Assets/CloudCode/MatchModule/MatchModule.ccmu +``` + +Always create the module with these commands, or, when they are missing, with **Assets > Create > Services > Cloud Code Module Script** and then **Cloud Behaviour Script**. Never hand-author the module's `.asmdef` files or its +`.ccmu`, because the Deployment window lists only modules that have a `.ccmu` asset. A module built from +hand-written asmdefs compiles, generates bindings and passes tests, but never appears in the Deployment +window, and nothing reports why. -The first behaviour in a folder opens the Cloud Behaviour Module Creator, which writes -`.ccmu` at the module root and scaffolds two assemblies: +The first command writes `.ccmu` at the module root and scaffolds the module's assemblies; the +second adds the behaviour and the CloudBehaviours assembly references. The module has two assemblies: | Folder | Assembly references | Platform | | :-- | :-- | :-- | @@ -91,7 +96,7 @@ Two entries in that `Client/` row are easy to get wrong, and both fail as `CCSG1 the generated client addresses its state through a `MultiplayerScopeProvider`. Installing `com.unity.services.multiplayer` is not sufficient on its own — the references have to be there too. -Use the table to check what the creator generated. The creator also wires the cloud reference, which a +Use the table to check what the commands generated. They also wire the cloud reference, which a hand-written client asmdef usually misses. The split matters: the cloud assembly has no engine references, so `UnityEngine` types are unavailable server-side, and the generator needs both assemblies to reference it. @@ -103,13 +108,12 @@ assembly name, GUID and script reference as it is: 1. Stop until the user confirms a rollback point, such as a commit in their version control or a backup copy of the project, so a failed repair has a clean way back. 2. Check the cloud asmdef against the `Cloud/` row of the table above and add any missing references. The - create menu refuses to add behaviours to a module whose cloud assembly lacks them. + create command refuses to add behaviours to a module whose cloud assembly lacks them. 3. Write `.ccmu` in the folder that holds both assembly folders, in the format and with the GUID rules in the `.ccmu` File Format section of `references/cloud-code-modules.md`. Take each GUID from the `guid:` line of the matching `.asmdef.meta` in this project, never from anywhere else, because a GUID resolves only in the project that minted it. -4. Verify: the `.ccmu` imports with zero console errors, and the module is listed in - **Services > Deployment** under the cloud asmdef's name. If either check fails, restore the rollback +4. Verify: `unity command script recompile` finishes with no errors in `script recompile_status`, and `unity command services.deployment list_items` lists the module under the cloud asmdef's name. If either check fails, restore the rollback point and read the console error before trying again. ## The authoring model @@ -419,17 +423,29 @@ endpoint, applies it, and only then raises `ScopeChanged`, with `Synchronized` i `ScopeChanged` handler can therefore read synchronized fields directly — they are already current, provided the hydrate succeeded (see below) — and a client that connects and does nothing else still holds server state. -If that first hydrate fails, `Error` is raised with `HydrationFailedOnConnect` *before* -`ScopeChanged`; `ScopeChanged` still follows, no `Synchronized` does, and the fields keep their -previous or default values. An `Error` handler therefore runs on a client that has not yet announced -its scope — `Scope` is already set, so calling `Hydrate()` from that handler is legal. +Every generated client arms the shared `ModuleHostWarmup.Default` (`Unity.Services.CloudCode`) when the +game loads, so the project's module host — the per-project process that runs every C# module, which the +service calls the invoker — is warmed once a player signs in, and the client waits for the warm-up before +its first hydrate. Read the warm-up's retry policy and idle timing in the installed package's docs, only +the `.md` files in `/Library/PackageCache/com.unity.services.cloudcode@*/Documentation~/`, +not from memory, because they change between package versions; read them again if a warm-up fails. If the host never becomes ready, the client +stops through `Fatal` with `InvokerUnavailable`: it is disabled before it hydrates or raises +`ScopeChanged`, and `EnableClient()` asks for another warm-up. A client on its own `IUnityServices` +instance (a virtual player) gets a private warm-up that `DisableClient()` resets. A project without +behaviour clients, or one that wants the host warm before the first native module call, arms the same +instance itself with `ModuleHostWarmup.Default.Arm()`; it waits for services and sign-in on its own. +Warming does not make a freshly deployed module callable any sooner. + +If that first hydrate fails the client stops the same way: `Fatal` with `HydrationFailedOnConnect`, +the scope withdrawn, no `ScopeChanged` for it and no `Synchronized`. A `ScopeChanged` that finds +`Scope` set therefore means the module host is up and the synchronized fields hold the server's +current state — it is the safe point to start calling the behaviour. Every RPC return also carries the caller's fresh view of synchronized state, so a client that calls an RPC does not need to hydrate either. -That leaves `Hydrate()` for two cases: catching up inside a live scope after a period of not -listening, and recovering from `HydrationFailedOnConnect`. A reconnect is not one of them — it -re-resolves the scope, which hydrates. +That leaves `Hydrate()` for one case: catching up inside a live scope after a period of not +listening. A reconnect is not one — it re-resolves the scope, which hydrates. Connecting costs one hydrate RPC per scope resolution, per client. A pooled client toggled repeatedly, or many behaviours on one player, pays it each time. @@ -438,25 +454,49 @@ repeatedly, or many behaviours on one player, pays it each time. Two events, split by whether the client survives. -`Fatal` carries a `CloudBehaviourException` whose `Reason` is one of `Unknown`, `SubscriptionError`, -`Kicked`, or `AmbiguousSessions`. The client is **already disabled** by the time handlers run — -`IsClientEnabled` is false and nothing further arrives until `EnableClient()` is called again. Do not -call it from the handler: a failure that reproduces immediately would recurse. `AmbiguousSessions` in -particular means the project has multiple active sessions and the binding cannot guess — set -**Target Session Type** in the Inspector, or call `EnableClient(sessionType)`. +`Fatal` carries a `CloudBehaviourException` whose `Reason` is one of `Unknown`, +`SubscriptionError`, `Kicked`, `AmbiguousSessions`, `HydrationFailedOnConnect` or +`InvokerUnavailable`. The client is **already disabled** by the time handlers run — `IsClientEnabled` +is false, `Scope` is withdrawn and nothing further arrives until `EnableClient()` is called again. Do +not call it from the handler: a failure that reproduces immediately would recurse; schedule the retry +with a delay instead. `AmbiguousSessions` means the project has multiple active sessions and the +binding cannot guess — set **Target Session Type** in the Inspector, or call `EnableClient(sessionType)`. +`InvokerUnavailable` and `HydrationFailedOnConnect` are connect-time failures: the module host could +not be warmed, or the first hydrate failed, so the client never announced that scope. A call that +fails after the scope resolved throws to its caller and does not stop the client. `Error` carries a `CloudBehaviourError` and reports a failure the client **carries on from**: it keeps -its `Scope` and stays enabled. Read `Reason` to decide whether to retry. Today the only value besides -`Unknown` is `HydrationFailedOnConnect` — the client could not fetch server state when its scope -resolved, so synchronized fields still hold their previous or default values. Call `Hydrate()` to try -again. +its `Scope` and stays enabled. Its one reason besides `Unknown` is `MessageError` — a synchronization +or push-event message from the behaviour could not be read or applied, usually because the payload no +longer matches the client's generated types after a redeploy. The message is dropped: synchronized +fields are unchanged and neither the push event nor `MessageReceived` is raised for it. The detail +names the message type. Regenerate the client against the deployed module; there is nothing to retry +at runtime. ```csharp -Fatal.AddListener(e => Debug.LogError($"client stopped: {e.Reason}")); +Fatal.AddListener(e => +{ + switch (e.Reason) + { + case CloudBehaviourExceptionReason.AmbiguousSessions: + // Configuration problem: pick a session type; re-enabling will not help. + break; + case CloudBehaviourExceptionReason.InvokerUnavailable: + case CloudBehaviourExceptionReason.HydrationFailedOnConnect: + case CloudBehaviourExceptionReason.SubscriptionError: + case CloudBehaviourExceptionReason.Kicked: + StartCoroutine(ReEnableAfterDelay()); // never EnableClient() from inside the handler + break; + } +}); Error.AddListener(e => { - if (e.Reason == CloudBehaviourErrorReason.HydrationFailedOnConnect) - _ = Hydrate(); + switch (e.Reason) + { + case CloudBehaviourErrorReason.MessageError: + // Client and module disagree on a payload; regenerate the client. Nothing to retry. + break; + } }); ``` @@ -969,15 +1009,23 @@ breakpoints, and lets Play mode talk to real cloud logic without a round trip to failing at runtime. - A module whose source changed is **redeployed automatically** onto the running server — no stop/start cycle. Redeploy happens after a recompile, outside Play mode only. **Nothing deploys to the local server - during Play mode**, not even an explicit `services_deployment_item_deploy`, which is refused. A + during Play mode**, not even an explicit `services.deployment deploy_items`, which is refused. A `404 function-not-found` for an endpoint added while playing means the module isn't deployed yet: exit Play mode, wait for `Local Cloud Code server reloaded` in the Console, then re-enter. Same known limitation as modules: see - the Deploying via the Deployment Window section of `references/cloud-code-modules.md`. + the Deploying section of `references/cloud-code-modules.md`. - The server won't start without an active services environment: see the Running the Local Cloud Code Server section of `references/cloud-code-modules.md`. - On startup the server checks for port conflicts and a usable .NET runtime, and a server that dies during startup reports why. +- **Local is not a sandbox, and not every design can be rehearsed on it.** It isolates the behaviour's own + state and push traffic; everything the behaviour then calls - Cloud Save, Secret Manager, Lobby - + is the live service for the active environment, and its writes are real. Player identity is not validated + locally. Session membership *is*, against the real Lobby service, so a session id with no lobby behind it + fails locally the same way it fails deployed. The full table is in + `/Library/PackageCache/com.unity.services.cloudcode@*/Documentation~/Authoring/cloud_code_local_server.md`. +- Local or remote is decided **when Play mode is entered**, from whether the server is running, and the + server is stopped when the Editor quits - so the first Play session after reopening a project is remote. ### The binding Inspector @@ -1009,10 +1057,10 @@ deployment or connection problem. ### Deployment -CloudBehaviour modules appear in the **Deployment** window as Cloud Code modules and deploy from there to -the linked UGS project. A module asset is a `.ccmu` file; its inspector offers deployment actions and a -summary of the last successful deployment. The window finds modules only through their `.ccmu`, so a module -that is missing from it has no `.ccmu`. Repair it by adding one (see +CloudBehaviour modules deploy as Cloud Code modules, with +`unity command services.deployment deploy_items --paths `, to the linked UGS project. A module asset is a `.ccmu` file; its inspector offers deployment actions and a +summary of the last successful deployment. Deployment finds modules only through their `.ccmu`, so a module +missing from `services.deployment list_items` has no `.ccmu`. Repair it by adding one (see [Creating the module](#creating-the-module)). Names come from the **cloud assembly (asmdef) name**, not the `.ccmu` asset name. While the local server @@ -1102,7 +1150,7 @@ These compile and then do nothing, which is what makes them expensive: returns, the hydrate on connect, and `Hydrate()`. - **A module without a `.ccmu` never reaches the Deployment window.** Hand-written asmdefs compile and generate bindings, but nothing lists the module for deployment and nothing warns. Create new modules - through the menu, and repair an existing one by adding its `.ccmu` (see + with the create commands, and repair an existing one by adding its `.ccmu` (see [Creating the module](#creating-the-module)). - **Model types are data only.** Methods and constructors are not regenerated on the client — the stub carries the public fields and properties, nothing else. A computed or get-only property is error diff --git a/skills/build-live-game/references/cloud-code-modules.md b/skills/build-live-game/references/cloud-code-modules.md index e755838..f49be25 100644 --- a/skills/build-live-game/references/cloud-code-modules.md +++ b/skills/build-live-game/references/cloud-code-modules.md @@ -30,7 +30,7 @@ references to a .NET solution built outside Unity) and JavaScript **scripts**. F - [Generated Client Bindings](#generated-client-bindings) - [Legacy Modules (.ccmr) - Maintenance Only](#legacy-modules-ccmr---maintenance-only) - [Code Templates](#code-templates) -- [Deploying via the Deployment Window](#deploying-via-the-deployment-window) +- [Deploying](#deploying) - [Running the Local Cloud Code Server](#running-the-local-cloud-code-server) - [Error Handling](#error-handling) - [Error Messages](#error-messages) @@ -42,7 +42,8 @@ references to a .NET solution built outside Unity) and JavaScript **scripts**. F | Correct | Incorrect (do NOT use) | |---|---| | For a new C# module, author a `.ccmu` in the Editor | Scaffolding a `.sln`/`.csproj`/`.pubxml` for a new module -- that is legacy `.ccmr` | -| Create a `.ccmu` module with **Create > Services > Cloud Code Module Script** | Hand-writing a new module's `.asmdef` files -- a module without a `.ccmu` never appears in the Deployment window | +| Create a `.ccmu` module with `unity command services.cloudcode create_module`, or **Assets > Create > Services > Cloud Code Module Script** when the command is missing | Hand-writing the module's `.asmdef` files or `.ccmu` -- a module without a `.ccmu` from that command never appears in the Deployment window | +| Set Api Compatibility Level with `unity command settings.player set` | Calling `PlayerSettings.SetApiCompatibilityLevel` from evaluated C# -- the command checks the value and reports the result | | A `.ccmu` module's name is its **cloud asmdef** `name` | The `.ccmu` filename -- it is only a fallback | | `.ccmu` client bindings are generated at **compile time** from `[CloudModuleClient]` | Clicking **Generate Bindings** -- that is the `.ccmr` flow | | `[CloudCodeService]` on an injected parameter of a `.ccmu` endpoint | A bare one -- the server still injects it, but it leaks into the generated client binding | @@ -205,15 +206,48 @@ compile time. There is no solution to build, nothing to publish, and no NuGet re - Unity **6000.5** or newer. - `com.unity.services.cloudcode` **3.0.0** or newer. -- **Api Compatibility Level set to `.NET Standard 2.1`** in Player Settings. Any other level makes the - module compile fine and then fail to deploy with "Unsupported API Compatibility Level". +- **Api Compatibility Level set to `.NET Standard 2.1`**, because any other level makes the module + compile fine and then fail to deploy with "Unsupported API Compatibility Level". The API names this + level `NET_Standard`; `NET_Standard_2_0` is a deprecated alias for the same level. To set it: + + 1. Run `unity command settings.player get` and read `api-compatibility-level`. If it is `NET_Standard` + or `NET_Standard_2_0`, the level is already correct, so skip the remaining steps. + 2. Run the command below. Use it instead of calling `PlayerSettings.SetApiCompatibilityLevel` from + evaluated C#, because the command checks the value and returns the setting as it stands after the + change. If it rejects the key or the value, run + `unity command --query settings.player --detail full --format json` and use the key and value + names in the `settings.player set` parameter schema. + + ```bash + unity command settings.player set --settings '{"api-compatibility-level":"NET_Standard"}' --confirm true + ``` + + 3. Check that `api-compatibility-level` in the response is `NET_Standard` or `NET_Standard_2_0`. + 4. Run `unity status --until-ready`, because the change reloads the scripting domain and a command + sent before the reload finishes can fail. ### Create it -Right-click a folder under `Assets/` -> **Create > Services > Cloud Code Module Script** and fill in the -creation window. An agent without computer-use tools asks the user to run this menu step; with them, it -runs the step itself. The rest of this section describes what the Editor generates for you, so you can -recognise and check the result. It is not a list of files to write by hand. +Run `unity command --query create_module` first. If it lists nothing, the installed package predates the +Cloud Code commands: create the module with **Assets > Create > Services > Cloud Code Module Script** +instead, which makes the module and its first script, and skip the commands below. + +```bash +unity command services.cloudcode create_module --module-name MyModule --path Assets/CloudCode +unity command services.cloudcode create_module_script --script-name MyCloudCodeScript --module-path Assets/CloudCode/MyModule/MyModule.ccmu +``` + +The first creates the module (cloud assembly `MyModule`, the deployed name; client `MyModuleClient`), the +second its first script. Rerun `services.cloudcode create_module_script` against the module's `.ccmu` to add +more script pairs. + +The rest of this section describes what the commands generate for you, so you can recognise and check the +result. It is not a list of files to write by hand. + +Always use the commands, never hand-written asmdefs, because the Deployment window lists only modules that +have a `.ccmu` asset. A hand-built module compiles, generates bindings and passes tests, but never appears +in the Deployment window, and nothing reports why. If a module is missing from +`services.deployment list_items`, check for its `.ccmu` first. Always use the menu for a new module, because it writes the module's `.ccmu` asset along with both assemblies, and the Deployment window lists only modules that have a `.ccmu`. A module built from @@ -286,7 +320,14 @@ A GUID identifies an asset in one project only, so a value taken from anywhere e another module, a sample, an example in documentation -- resolves to nothing. Both keys are required; a `.ccmu` naming a GUID Unity cannot resolve fails to import and logs an error. -Creating the module through the Editor writes the file with the right values already in it. +Never write or edit a `.meta` file to get a GUID, because Unity replaces a GUID it rejects (malformed, or +already used by another asset) with a new one on import, and a `.ccmu` that copied the hand-written value +then resolves to nothing. If the `.asmdef.meta` does not exist yet, Unity has not imported the asmdef: run +`unity command script recompile`, then `unity status --until-ready`, and read the GUID from the `.meta` +Unity wrote. + +Creating the module with `services.cloudcode create_module` writes the file with the right values already in it. Do not write +a `.ccmu` by hand for a new module; only a repair of an existing module adds one by hand (see the CloudBehaviours reference). ### Deployed Module Name @@ -335,13 +376,13 @@ still compiles, and still deploys — it is simply wrong in ways you find out la | When | What is checked | How it surfaces | | :-- | :-- | :-- | | `.ccmu` import | only that both asmdef GUIDs resolve | console error, asset fails to import | -| **Create > Services > Cloud Code Module Script** into an existing module's `Cloud/` folder | Editor-only, no engine references, not auto-referenced, references Core + Apis | modal dialog: *"This Cloud Code module's server Assembly Definition (.asmdef) is missing or misconfigured..."*, and the script is not created | +| `services.cloudcode create_module_script` on an existing module | Editor-only, no engine references, not auto-referenced, references Core + Apis | the command fails with *"This Cloud Code module's server Assembly Definition (.asmdef) is missing or misconfigured..."*, and the script is not created | | Deploy | nothing about the asmdef flags; the only structural check is that two modules do not share a cloud assembly | per-item error status on each offending module in the Deployment window, logged as *"Assembly Failure -- Multiple CCMs reference the same assembly definition"* | -So the asmdef flags are effectively enforced only when you add a script through the menu. A hand-edited +So the asmdef flags are effectively enforced only when you add a script with the command. A hand-edited module is on the honour system — worth checking by eye, because nothing else will. (Deploy does make other checks unrelated to the asmdef — Api Compatibility Level and whether the project compiles — -covered under [Deploying via the Deployment Window](#deploying-via-the-deployment-window).) +covered under [Deploying](#deploying).) ### Client Assembly (`Client/MyModuleClient.asmdef`) @@ -505,12 +546,6 @@ namespace MyModule.Client } ``` -### Adding Another Script to an Existing Module - -Right-click the module's **`Cloud/` folder** -> **Create > Services > Cloud Code Module Script**. The same -menu item detects the existing module and creates the cloud/client pair inside it instead of starting a -new module. Creating a script in the `Client/` folder is rejected -- always start from `Cloud/`. - --- ## Module State and Persistence @@ -847,6 +882,12 @@ which cannot author `.ccmu`. A legacy module is a .NET class library (.NET 8, up to .NET 10) living outside `Assets/`, built and published by the Deployment Window, and referenced from Unity by a `.ccmr` file. +If a project's `.ccmr` is missing, recreate the reference (not the module) with +`unity command services.cloudcode create_module_reference --path Assets/MyModule.ccmr`. Not every +`com.unity.services.cloudcode` release ships the Cloud Code CLI commands, so when +`unity command --query create_module_reference` finds nothing, use +**Assets > Create > Services > Cloud Code C# Module Reference** instead. + ### Directory Structure Place the module at the **project root** (alongside `Assets/`). Unity does not scan the project root, so no `~` suffix is needed. @@ -1161,11 +1202,11 @@ async Task Unsubscribe() --- -## Deploying via the Deployment Window +## Deploying -1. Open **Services > Deployment** in the Unity Editor. -2. All `.js`, `.ccmu` and `.ccmr` files under `Assets/` are listed. **Select only what you mean to deploy** - -- deploying everything can overwrite modules that are not ready to go out. +1. Deploy with `unity command services.deployment deploy_items --paths `. +2. **Pass only what you mean to deploy** -- deploying everything can overwrite modules that are not ready + to go out. 3. A `.ccmu` deploys the compiled cloud assembly, under the **cloud asmdef's name**. Its client bindings already exist -- they were generated when Unity compiled the module, so there is nothing to regenerate. 4. A `.ccmr` builds and publishes its solution. After it deploys, generate or regenerate its bindings @@ -1176,8 +1217,9 @@ it, and nothing is deployed to it while the Editor is in play mode. Edit and dep enter play mode. Changes made during play mode do not reach the local server until you exit play mode and deploy again. -A `.ccmu` deploy fails with **"Unsupported API Compatibility Level"** unless the project's Player Settings -have Api Compatibility Level on `.NET Standard 2.1`. It also fails if the project has compile errors -- +A `.ccmu` deploy fails with **"Unsupported API Compatibility Level"** unless the project's Api +Compatibility Level is `.NET Standard 2.1` -- set it with `unity command settings.player set` (see +[Requirements](#requirements)). It also fails if the project has compile errors -- the module is deployed from its compiled assembly, so it has to build first. **Deploying a `.ccmu` needs a running Editor.** Nothing packages a `.ccmu` outside the Editor, and @@ -1185,36 +1227,37 @@ the module is deployed from its compiled assembly, so it has to build first. to run the Editor. Only legacy `.ccmr` modules deploy without one, through their `.sln`; do not create a `.ccmr` to get around this. -**Local development needs no deploy.** While the local Cloud Code server runs (Cloud Code button on the -Editor toolbar > **Start Local Server**; it needs an active environment), each successful compile redeploys +**Local development needs no deploy.** While the local Cloud Code server runs +(`unity command services.cloudcode start_local_server`; it needs an active environment), each successful compile redeploys changed `.ccmu` modules onto it, outside Play mode. **Nothing deploys to the local server during Play mode**, not even an explicit deploy, which is refused: exit Play mode before recompiling and deploying. A `404 function-not-found` for an endpoint added while playing means exactly this; exiting Play mode redeploys it and logs `Local Cloud Code server reloaded`. **Known limitation.** An unfocused Editor doesn't notice file edits or run the local auto-deploy until it -regains focus. After editing module code without focusing the Editor, run `unity command recompile`, then -deploy with the `Deploy.cs` script from -`references/deployment.md`: while the local -server runs, the deploy targets it, not the environment. Stop the server before deploying remotely. - -To deploy without the window, run the deploy script in -the Trigger Deployment Programmatically section of `references/deployment.md`. +regains focus. After editing module code without focusing the Editor, run `unity command script recompile`, then +deploy with `unity command services.deployment deploy_items --paths `: while the local server runs, the deploy targets it, not the environment. Stop the server before +deploying remotely. --- ## Running the Local Cloud Code Server The local server runs the project's modules in a process on this machine, and the SDK routes -`CallModuleEndpointAsync` to it instead of the cloud. Start and stop it with the Cloud Code button on the -Editor toolbar (**Start Local Server** / **Stop Local Server**), outside Play mode; it needs Unity 6000.3+. -Redeploy on compile, and what to do when the Editor is unfocused, are covered in -[Deploying via the Deployment Window](#deploying-via-the-deployment-window). +`CallModuleEndpointAsync` to it instead of the cloud. Redeploy on compile, and what to do when the Editor is +unfocused, are covered in [Deploying](#deploying). + +```bash +unity command services.cloudcode start_local_server # compiles the modules, spawns the server, mode becomes "Local" +unity command services.cloudcode get_local_server_status # mode, status, pid, port, last failure +unity command services.cloudcode stop_local_server # mode back to "Remote" +``` + +The local server needs Unity 6000.3+. Start and stop both refuse while the Editor is in Play mode. The server listens on port **14750** by default. To run several Editors, each with its own local server, -give each project a distinct port in **Edit > Project Settings > Services > Cloud Code > Local Debugging > -Port** while its server is stopped; a port already in use fails startup with *"Server Port is not -available."* +give each project a distinct port with `unity command services.cloudcode set_local_server_port --port ` +before starting its server; a port already in use fails startup with *"Server Port is not available."* Play mode reads the port and whether a server is running from Editor preferences shared by every Editor on the machine, so calls go to the most recently started server, and stopping any Editor's server sends the others' calls to the cloud. @@ -1227,7 +1270,16 @@ Startup validates the environment first, and a project with no active environmen > Selector, found under Edit → Project Settings → Services → Environments, to set it. A fresh clone or a CI checkout has no active environment, so this is usually the first thing that fails. -Set one in **Edit > Project Settings > Services > Environments** (ask the user, or drive the Editor UI). +Set one first: + +```bash +unity command services.environment list # name + id + which is default +unity command services.environment set_active_by_name --name # an environment from the list, not blindly production +unity command services.environment get_active_name # confirm +``` + +`services.environment set_active_by_name` refreshes the environment list before resolving the name, so it +works on a project that has never fetched one. An unknown name throws `EnvironmentNotFoundException`. --- @@ -1266,7 +1318,7 @@ have it. | Error string | Cause | Fix | | :-- | :-- | :-- | -| `Unsupported API Compatibility Level` | The project's Api Compatibility Level is not `.NET Standard 2.1` | Set it in Player Settings, then redeploy the `.ccmu` | +| `Unsupported API Compatibility Level` | The project's Api Compatibility Level is not `.NET Standard 2.1` | Set it with `unity command settings.player set` (see [Requirements](#requirements)), then redeploy the `.ccmu` | | `Invalid constructor: type X must have exactly one public constructor` | The module class has no public constructor or several | Keep exactly one public constructor | | `Function's ... class in module ... requires a scope and must be called with a scope` | A `[StateScope]` function was called without a scope, or with the wrong one | Pass a `CloudCodeScope` that matches the class's `[StateScope]`, or use the generated client | | `This Cloud Code module's server Assembly Definition (.asmdef) is missing or misconfigured...` | The cloud asmdef is not Editor-only, has engine references, is auto-referenced, or lacks the Core and Apis references | Fix the asmdef, then create the script again | diff --git a/skills/build-live-game/references/deployment.md b/skills/build-live-game/references/deployment.md index 725ac71..d4c4ff9 100644 --- a/skills/build-live-game/references/deployment.md +++ b/skills/build-live-game/references/deployment.md @@ -4,6 +4,7 @@ - [Overview](#overview) - [Supported Service Integrations](#supported-service-integrations) +- [Link the Project](#link-the-project) - [Workflow](#workflow) - [Deployment Definitions (.ddef)](#deployment-definitions-ddef) - [JSON Schema](#json-schema) @@ -15,8 +16,8 @@ - [SeverityLevel](#severitylevel) - [DeploymentProvider (Abstract)](#deploymentprovider-abstract) - [IDeploymentItem](#ideploymentitem) - - [Code Template -- Register a Custom Provider](#code-template--register-a-custom-provider) - - [Code Template -- Trigger Deployment Programmatically](#code-template--trigger-deployment-programmatically) + - [Code Template: Register a Custom Provider](#code-template-register-a-custom-provider) + - [Code Template: Trigger Deployment Programmatically](#code-template-trigger-deployment-programmatically) ## Overview @@ -29,7 +30,7 @@ Editor-only package providing the **Deployment Window** (Services > Deployment). Each service package registers its own file types with the Deployment Window. Install the relevant service package to enable its file types. -| Service | Package | File Type(s) | Min Version | +| Service | Package | File Type(s) | Min Version to Deploy the File Type | |---|---|---|---| | Cloud Code Scripts | `com.unity.services.cloudcode` | `.js` | 2.1.0 | | Cloud Code C# Modules (native) | `com.unity.services.cloudcode` | `.ccmu` | 3.0.0 | @@ -44,13 +45,15 @@ Each service package registers its own file types with the Deployment Window. In | Scheduler | `com.unity.services.tooling` | `.sched` | 1.4.2 | | Deployment Definitions | `com.unity.services.deployment` | `.ddef` | -- | +## Link the Project + +Deploying and runtime service calls need the project linked to a Unity Cloud project. Follow `references/link-cloud.md`. Deploying through `unity ugs` with service-account keys needs no Editor sign-in. + ## Workflow 1. Add `com.unity.services.deployment` via Package Manager. -2. Open **Services > Deployment**. -3. Select the target environment in the dropdown. -4. Choose files to deploy (or select all). -5. Click **Deploy**. +2. Set the target environment: `unity command services.environment set_active_by_name --name `. +3. Deploy the files: `unity command services.deployment deploy_items --paths `. ## Deployment Definitions (.ddef) @@ -58,7 +61,7 @@ A Deployment Definition scopes the Deployment Window to a subset of files. Usefu **File extension:** `.ddef` -**Create via:** Right-click in Project window > Create > Unity Gaming Services > Deployment Definition +**Create via:** `unity command services.deployment create_definition --path Assets/MyDefinition.ddef` ### JSON Schema @@ -81,7 +84,7 @@ A Deployment Definition scopes the Deployment Window to a subset of files. Usefu - **Without a `.ddef`:** the Deployment Window discovers and deploys all UGS config files under `Assets/`. - **With a `.ddef` selected:** only files within the definition's scope (minus excluded paths) are shown and deployed. -- Multiple `.ddef` files can exist in one project; select which one to use in the Deployment Window dropdown. +- Multiple `.ddef` files can exist in one project; `unity command services.deployment list_definitions` lists them. ## Programmatic API @@ -169,7 +172,7 @@ Subclass this to expose your own deployable assets to the Deployment Window. | `Status` | `DeploymentStatus` (message + severity) | | `States` | `ObservableCollection` -- local asset validation states | -### Code Template -- Register a Custom Provider +### Code Template: Register a Custom Provider ```csharp using UnityEditor; @@ -194,23 +197,22 @@ static void RegisterProvider() > admin API (e.g. `adminClient.CloudSaveData.SetCustomItem` for Cloud Save game data). > See `references/apis.md` for the full `IAdminClient` interface and code templates. -### Code Template -- Trigger Deployment Programmatically +### Code Template: Trigger Deployment Programmatically -Run it with `unity command run_script --file AgentScripts/Deploy.cs --entry Deploy.Run --args '[["Assets/MyConfig.rc"]]'` -(needs the `com.unity.pipeline` and `com.unity.services.deployment.api` packages; keep the file outside `Assets/`). `DeploymentWindow` throws -*"Deployment Window must be opened for this operation."* until the window is open, so the script opens it -and waits. +Prefer `unity command services.deployment deploy_items`; use this only from Editor code. +`DeploymentWindow` throws *"Deployment Window must be opened for this operation."* until the window is +open, so open it and wait first. Await the calls; never `.Wait()`, which deadlocks the main thread. ```csharp -// AgentScripts/Deploy.cs — deploys to the active environment. Await; never .Wait(), which deadlocks the main thread. using System.Linq; using System.Threading.Tasks; using Unity.Services.DeploymentApi.Editor; using UnityEditor; +using UnityEngine; public static class Deploy { - public static async Task Run(string[] paths) + public static async Task Run(string[] paths) { var deployments = Deployments.Instance; if (!(deployments.DeploymentWindow is EditorWindow)) @@ -218,14 +220,14 @@ public static class Deploy for (var i = 0; i < 100 && !(deployments.DeploymentWindow is EditorWindow); i++) await Task.Delay(100); - var items = deployments.DeploymentWindow.GetFromFiles(paths); - var found = items.Where(item => item != null).ToList(); - // Deploy all items instead: await deployments.DeploymentWindow.Deploy(deployments.DeploymentWindow.GetAllDeploymentItems()); + var window = deployments.DeploymentWindow; + window.DeploymentStarting += items => Debug.Log($"Deploying {items.Count} items..."); + window.DeploymentEnded += items => Debug.Log($"Deployment complete: {items.Count} items"); + + // Deploy everything instead: await window.Deploy(window.GetAllDeploymentItems()); + var found = window.GetFromFiles(paths).Where(item => item != null).ToList(); if (found.Count > 0) - await deployments.DeploymentWindow.Deploy(found); - return string.Join("\n", paths.Select((path, i) => items[i] == null - ? $"{path}: not a deployable item" - : $"{path}: {items[i].Status.MessageSeverity} {items[i].Status.Message} {items[i].Status.MessageDetail}")); + await window.Deploy(found); } } ``` diff --git a/skills/build-live-game/references/link-cloud.md b/skills/build-live-game/references/link-cloud.md index b6f75a5..5f303eb 100644 --- a/skills/build-live-game/references/link-cloud.md +++ b/skills/build-live-game/references/link-cloud.md @@ -3,9 +3,10 @@ UGS calls need a linked Unity Cloud project ID. Linking writes `ProjectSettings/ProjectSettings.asset`: do it only when the task needs service calls or asks to link, after the restore point. Pass `--project-path ` to every `unity command` below, because without it the CLI drives the Editor of the shell's current folder, which may be another project. 1. A non-empty `cloudProjectId` in `ProjectSettings/ProjectSettings.asset` means it is linked: skip the rest. -2. Without `--cloud-project`, the CLI reuses `UNITY_CLOUD_PROJECT`, then the saved default (`defaultCloudProjectId` from `unity cloud project current --format json`), and creates a project only when both are empty. To reuse one, pass `--cloud-project `. If either is set and the user wants a new one, ask first: `unity cloud project clear-default` clears only the saved default, and the user must unset `UNITY_CLOUD_PROJECT` in their own shell. -3. Check `Packages/manifest.json` for `com.unity.pipeline`: closing gracefully, `--until-ready` and `script eval` need it. If it is missing, add it with `unity pipeline install --project-path ` (Unity 6.0+) and say so in the report. If it can't be added, ask the user to save and close the Editor themselves, and in step 5 check only the asset. -4. `unity close ` exits without saving, so ask the user to save their work first, then run it: an open Editor keeps the old link and can save it back over the new one. -5. Run `unity projects link cloud --format json`, plus `--cloud-project ` when reusing. When it will create a project, first ask whether the game is directed at children under 13 and add `--coppa compliant` if so: the default is `not_compliant`. Never pass `--coppa` with `--cloud-project` (error `COPPA_ARGS_CONFLICT`); change an existing project's COPPA setting in the Unity Cloud dashboard. -6. Verify: if `data.editor.restartRequired` is `true`, an Editor still had the project open: close it, then check the asset still holds the new ID, and if not rerun with `--cloud-project `. Reopen with `unity open --until-ready --format json` (a plain `unity open` returns before the Editor can answer commands) and check `cloudProjectId` in the asset and `CloudProjectSettings.projectId` (via `unity command script eval --project-path `) equal `data.cloudProject`'s ID. On failure, stop and report the error code. -7. Never hand-edit the asset or write an Editor-side linker: a manual edit can mismatch project and organization IDs. +2. Ask the user before linking. Run `unity auth status`; if it reports signed out, run `unity auth login` and ask the user to finish signing in in the browser it opens, because linking needs a signed-in account. +3. Without `--cloud-project`, the CLI reuses `UNITY_CLOUD_PROJECT`, then the saved default (`defaultCloudProjectId` from `unity cloud project current --format json`), and creates a project only when both are empty. To reuse one, pass `--cloud-project `. If either is set and the user wants a new one, ask first, then clear the saved default with `unity cloud project clear-default` and remove `UNITY_CLOUD_PROJECT` from the link command's own environment in step 6 (for example `env -u UNITY_CLOUD_PROJECT unity projects link cloud ...`), because your shell inherited it and the user unsetting it in theirs doesn't change yours. Recheck both are empty before step 6 creates the project. +4. Check `Packages/manifest.json` for `com.unity.pipeline`: closing gracefully, `--until-ready` and `script eval` need it. If it is missing, add it with `unity pipeline install --project-path ` (Unity 6.0+), say so in the report, and run `unity status --until-ready --project-path ` before closing, because an open Editor loads Pipeline only after it refreshes: on `STATUS_PIPELINE_LOAD_PENDING`, ask the user to focus the Editor and check again. If it can't be added or doesn't load, ask the user to save and close the Editor themselves, and in step 7 check only the asset. +5. `unity close ` exits without saving, so ask the user to save their work first, then run it: an open Editor keeps the old link and can save it back over the new one. +6. Run `unity projects link cloud --format json`, plus `--cloud-project ` when reusing. When it will create a project, first ask whether the game is directed at children under 13 and add `--coppa compliant` if so: the default is `not_compliant`. Never pass `--coppa` with `--cloud-project` (error `COPPA_ARGS_CONFLICT`); change an existing project's COPPA setting in the Unity Cloud dashboard. +7. Verify: if `data.editor.restartRequired` is `true`, an Editor still had the project open: close it, then check the asset still holds the new ID, and if not rerun with `--cloud-project `. Reopen with `unity open --until-ready --format json` (a plain `unity open` returns before the Editor can answer commands) and check `cloudProjectId` in the asset and `CloudProjectSettings.projectId` (via `unity command script eval --project-path `) equal `data.cloudProject`'s ID. Without Pipeline, `--until-ready` times out, so reopen with plain `unity open `, check only the asset's ID, and report that the Editor-side check was not run. On failure, stop and report the error code. +8. Never hand-edit the asset or write an Editor-side linker: a manual edit can mismatch project and organization IDs. diff --git a/skills/build-live-game/references/player-account.md b/skills/build-live-game/references/player-account.md index f6eeabe..1252230 100644 --- a/skills/build-live-game/references/player-account.md +++ b/skills/build-live-game/references/player-account.md @@ -212,6 +212,18 @@ Namespace: `Unity.Services.Authentication.PlayerAccounts`. Access via `PlayerAcc If using any authentication other than anonymous, it requires the Unity identity provider to be enabled in **Project Settings > Services > Authentication > Identity Providers**. +### Turn On Unity Player Accounts + +Unity sign-in needs the project's Player Accounts client and the Authentication `unity` identity provider that points at it. Turning Player Accounts on creates both, so never add the `unity` provider any other way. + +1. Read the commands' arguments with `unity command --query services.authentication.player_accounts --format json`, because they can differ between package versions. If the group isn't listed, the project's Authentication package doesn't include these commands: ask the user to add Unity Player Accounts in the Unity Dashboard (Authentication > Identity Providers > Add provider > Unity Player Accounts), then continue at step 4. +2. Check that the project is linked to a Unity project ID (**Edit > Project Settings > Services**), because the commands act on the linked project. If it isn't, follow Link the Project in `references/deployment.md`. +3. Run `unity command services.authentication.player_accounts enable --name "" --platforms `. The name is what players see when they sign in; ask the user if you can't tell it from the project. The platforms are the ones the game signs players in on (`mobile`, `desktop`). The command is safe to run again: it creates the client or updates it, and waits until the client is ready. +4. Get the Client ID into the project. `PlayerAccountService` reads it from `Assets/Resources/UnityPlayerAccountSettings.asset`, and `enable` doesn't write that asset. Ask the user to open **Edit > Project Settings > Services > Authentication**, which copies the `unity` provider's Client ID into it when it lists the identity providers, or to enter the ID in **Edit > Project Settings > Services > Unity Player Accounts**. Don't write the asset by hand. +5. Confirm that the `clientId` in `Assets/Resources/UnityPlayerAccountSettings.asset` matches the project's Client ID, because an empty one makes sign-in fail with `MissingClientId`. + - With the commands, run `unity command services.authentication.player_accounts get`, check that `Status` is `Ready`, and compare its Client ID. If it reports `NotSetUp` or `ClientMissing`, run `enable` again. + - Without them (the Dashboard route in step 1), ask the user for the Client ID the Dashboard shows for Unity Player Accounts and compare that. Tell the user this check depended on them. + ### PlayerAccountService API | Member | Type | Description | @@ -440,10 +452,16 @@ if (result.TryGetValue("player_level", out var item)) Writes to Protected and Custom buckets must go through a Cloud Code module. The module uses `IGameApiClient` with the service token to call Cloud Save server-side APIs. -Create it with the Editor rather than by hand: right-click a folder under `Assets/` → -**Create > Services > Cloud Code Module Script** and name it `PlayerAccountModule`. See +Create it with these commands: + +```bash +unity command services.cloudcode create_module --module-name PlayerAccountModule --path Assets/CloudCode +unity command services.cloudcode create_module_script --script-name PlayerAccountModule --module-path Assets/CloudCode/PlayerAccountModule/PlayerAccountModule.ccmu +``` + +See the Creating a Cloud Code Module section of `references/cloud-code-modules.md`. -The Editor generates the following — use the list to check what you got, not as files to type out. There is +The commands generate the following — use the list to check what you got, not as files to type out. There is no `.sln`, `.csproj`, `.pubxml` or test project. - [ ] `Assets/CloudCode/PlayerAccountModule/PlayerAccountModule.ccmu` (holds the two asmdef GUIDs) @@ -452,7 +470,7 @@ no `.sln`, `.csproj`, `.pubxml` or test project. - [ ] `Client/PlayerAccountModuleClient.asmdef` — references the cloud assembly - [ ] `Client/PlayerAccountModuleClient.cs` — `[CloudModuleClient(typeof(PlayerAccountModule))]` partial -One file the Editor does **not** generate, which this module needs because its endpoints inject +One file the commands do **not** generate, which this module needs because its endpoints inject `IGameApiClient`: - [ ] `Cloud/CloudSetup.cs` — an `ICloudCodeSetup` calling `config.AddGameApiClient()` diff --git a/skills/build-live-game/references/remote-config.md b/skills/build-live-game/references/remote-config.md index 09f3edb..2b71925 100644 --- a/skills/build-live-game/references/remote-config.md +++ b/skills/build-live-game/references/remote-config.md @@ -8,7 +8,7 @@ - [.rc File Format](#rc-file-format) - [Game Overrides](#game-overrides) - [Common Patterns](#common-patterns) -- [Code Template -- Load JSON Config](#code-template--load-json-config) +- [Code Template: Load JSON Config](#code-template-load-json-config) ## Overview @@ -59,7 +59,7 @@ var obj = token.ToObject(); ``` - **Create via:** Right-click in Project window > Assets > Create > Services > Remote Config -- **Deploy via:** the Deployment Window (Services > Deployment) +- **Deploy via:** `unity command services.deployment deploy_items --paths ` - The `types` block is needed only for JSON entries; `string`, `int`, `bool`, `float`, and `long` are auto-detected. ## Game Overrides @@ -77,7 +77,7 @@ Game Overrides (via `com.unity.services.tooling`) override Remote Config values - **Feature flags** stored as booleans for toggling game features server-side. - **Version-specific config** with server-side updates -- change game balance without shipping a new client build. -## Code Template -- Load JSON Config +## Code Template: Load JSON Config ```csharp using Unity.Services.RemoteConfig; diff --git a/skills/build-live-game/references/tooling.md b/skills/build-live-game/references/tooling.md index 8c4e84f..a193fe2 100644 --- a/skills/build-live-game/references/tooling.md +++ b/skills/build-live-game/references/tooling.md @@ -28,7 +28,7 @@ Tooling provides two cloud resource file types deployed through the Deployment W | Access Control | `.ac` | Permit or deny player/service-account access to UGS services on a URN basis | | Game Overrides | `.ugo` | A/B testing and audience targeting by overriding Remote Config values for player segments | -Both file types are created via right-click in the Project window → **Create > Unity Gaming Services** and deployed via **Services > Deployment**. +Both file types are created via right-click in the Project window → **Create > Unity Gaming Services** and deployed with `unity command services.deployment deploy_items`. --- diff --git a/skills/build-live-game/references/ugs-cli.md b/skills/build-live-game/references/ugs-cli.md index d887217..ac1e095 100644 --- a/skills/build-live-game/references/ugs-cli.md +++ b/skills/build-live-game/references/ugs-cli.md @@ -75,12 +75,14 @@ unity ugs fetch . -s remote-config -e production | Resource | Headless path | |---|---| -| `.ccmu` (native C# module) | **Not the UGS CLI** — `unity ugs deploy` skips `.ccmu`. The Editor compiles the module and deploys it: the Deployment Window, or headlessly the `Deploy.cs` template in `references/deployment.md`. | +| `.ccmu` (native C# module) | **Not the UGS CLI** — `unity ugs deploy` skips `.ccmu`. The Editor compiles the module and deploys it: `unity command services.deployment deploy_items --paths Assets/MyModule/MyModule.ccmu`. | | `.ccmr` (legacy module) | `unity ugs deploy` skips the `.ccmr` itself — pass the `.sln` it points at: `unity ugs deploy Module~/Module.sln`. The CLI runs `dotnet publish` (needs a .NET SDK on PATH). The Deployment Window deploys the `.ccmr` directly. | | `.ccm` (packaged module) | `unity ugs deploy .ccm` | | `.rc`, `.ac`, `.lb`, `.js`, `.tr`, `.sched` | `unity ugs deploy ` and `unity ugs fetch `, or the Deployment Window. `--dry-run` first; `--reconcile` deletes remote content not in the deploy. `unity ugs tr new-file ` / `unity ugs sched new-file ` generate a default trigger / schedule config. | -| `.ugo` (Game Overrides) | **Not the UGS CLI** — `unity ugs deploy` skips `.ugo`. Deploy through the Deployment Window, or headlessly the `Deploy.cs` template in `references/deployment.md`. | +| `.ugo` (Game Overrides) | **Not the UGS CLI** — `unity ugs deploy` skips `.ugo`. Deploy with `unity command services.deployment deploy_items --paths Assets/MyOverrides.ugo`. | ## Credentials and Environment `unity ugs deploy`/`fetch` authenticate using whichever CLI credential is active — a service account (`unity ugs login` or its env vars) or, from 2.0.0+, Unity Hub sign-in (see [Auth and Project Setup](#auth-and-project-setup)) — never as the signed-in Editor user, and take the environment as an argument (`-e `). An Editor deploy uses the Editor's own credentials and the project's *active* environment — except that while the local Cloud Code server runs, a Cloud Code module deploy goes to that server instead. Stop the local server before deploying a module remotely. + +The CLI keeps its own target, which can differ from the Editor's. Before a `unity ugs` command that writes to the backend, run `unity ugs config get project-id` and `unity ugs config get environment-name`, and confirm they match the project ID the Unity project is linked to and the environment the user asked for. If either differs, stop and ask the user. diff --git a/skills/build-multiplayer-game/SECURITY.md b/skills/build-multiplayer-game/SECURITY.md new file mode 100644 index 0000000..213ec05 --- /dev/null +++ b/skills/build-multiplayer-game/SECURITY.md @@ -0,0 +1,26 @@ +# Security notes: build-multiplayer-game + +When testing host and client behaviour, this skill has the agent run C# inside the user's open Unity Editor, and inside Multiplayer Play Mode clone Editors of the same project, through `unity command script eval`. Automated skill scanners flag that as a powerful capability. It is intentional, and it is limited by the safeguards below. + +## Accepted risks + +| Risk | Capability | Why it is accepted | +|---|---|---| +| `SEC_POWER_CAP` | Runs C# in the user's open Editor and its Multiplayer Play Mode clones through `unity command script eval`, and triggers script recompiles and asset reimports through `unity command` | It only reaches Editors of the user's own project that are already open on their own machine, as that user, so it grants nothing they couldn't do themselves. `eval` sits behind the Pipeline capability gate. No code fetched from a remote source is run. Where a named `unity command` covers a step, the skill uses that instead of `eval`. | + +## What it changes + +The skill writes to the user's project and machine, not only reads. It asks the user before each of the larger changes below. + +- **Packages:** adds the packages the chosen stack needs to `Packages/manifest.json`: `com.unity.services.multiplayer`, `com.unity.netcode.gameobjects` or `com.unity.netcode`, `com.unity.dedicated-server` for a dedicated server, and `com.unity.pipeline` (through the `unity-cli` skill) when the Editor commands are missing. +- **Editor modules:** installs a dedicated server module (`linux-server`, `windows-server` or `mac-server`) with `unity install-modules`, a 0.5–2 GB download. +- **Cloud project:** links the project to a Unity Cloud project with `unity projects link cloud`, which can create a new project in the user's organization. The skill reuses an existing project unless the user agrees to a new one, and asks the COPPA question before creating one. +- **Project files and settings:** creates scripts, prefabs and Play Mode Scenario assets, turns on Multiplayer Roles, sets which role keeps each GameObject and component (what a client or server strips), sets a scenario player's Multiplayer Role, turns on the project's Run in Background setting, and changes the netcode bootstrap setting. + +## Mitigations + +- **Only the user's own Editors.** Commands go to the Editor open on this machine and to clones of that same project. They can't reach another machine or another user's Editor. +- **Capability gate.** `eval` is only available when the project's Pipeline package provides it. +- **No remote code.** The agent runs C# it writes for the user's task, such as test-only host and join hooks. Nothing downloaded from outside is executed. +- **Clones drive the game, not the project.** The skill tells the agent to use clone Editors only to run and read the game, never to change project assets. +- **Named commands first.** When a dedicated `unity command` covers a step, the skill uses it instead of `eval`. diff --git a/skills/build-multiplayer-game/SKILL.md b/skills/build-multiplayer-game/SKILL.md new file mode 100644 index 0000000..b1c0f0b --- /dev/null +++ b/skills/build-multiplayer-game/SKILL.md @@ -0,0 +1,216 @@ +--- +name: build-multiplayer-game +description: >- + Builds Unity online multiplayer, from matchmaking to gameplay sync. Make sure to use this skill when the user asks to add online play, host or join games, or fix lag, desync or connection failures. Not for voice chat or backend features. +allowed-tools: + - WebFetch + - WebSearch +--- + +# Build multiplayer game + +The **session layer** (Unity Multiplayer Services) creates, finds and connects the match; **netcode** synchronizes gameplay inside it. A **game session** is the running netcode world, from `StartAsHost`/`Connect` until `Shutdown`; a lobby or session before it is not one, so no ghost may be touched yet. + +## Before you start + +Before a workflow or diagnosis, read the doc pages from [Documentation](#documentation) that cover it, and name the files you read, because your training knowledge may be for the wrong version. + +Prefer `WebFetch` over `WebSearch`, and fetch only what you need. Replace `` with the package's major.minor resolved in `Packages/packages-lock.json` (e.g. `7.2`); docs.unity.com URLs are unversioned. If that version's page is not published (404), read the installed package's `Documentation~` copy, never an older version's page, because older pages describe a different API. If neither exists, read the package source and report the page missing. + +Run Editor commands via the `unity-cli` skill. Fully qualify types in `script eval` snippets (or add `using` lines), because an unqualified type outside `UnityEngine` fails with CS0103. + +Do only what's asked. Don't change unrelated assets or files. Avoid long explanations. Never leave verification code in the user's script. Never build logging or detection they didn't ask for. Create a restore point you can roll back to if your changes fail. + +## Documentation + +**Multiplayer Services.** The [documentation map](https://docs.unity.com/en-us/mps-sdk/llms.txt) is authoritative over memory; don't mention `llms.txt` to the user. If it is unreachable, use the installed `com.unity.services.multiplayer` source. Pages (as `.md`): + +- `create-session`, `join-session`, `matchmake-session`, `matchmake-lobby` (quick join) +- `session-networking`, `session-host-migration`, `game-server-hosting-support` (dedicated servers, backfill) +- `build-with-netcode-for-entities` (how the default network handler creates worlds), `lobby-error-messages` + +**Netcode packages.** For `` below, read `/Library/PackageCache/@*/Documentation~/` `.md` files first (`"source": "builtin"`: the Editor install's `Resources/PackageManager/BuiltInPackages//`; before install, the version Package Manager would resolve). Otherwise fetch `https://docs.unity3d.com/Packages/@/manual/.html`. + +Unity Netcode (`com.unity.netcode`): + +- Topology and host modes: `choose-network-topology`, `client-hosted`, `binary-worlds-host-mode`, `single-world-host-mode` +- Ghosts, prediction, physics, lag compensation: `ghosts`, `prediction-n4e`, `physics`, `server-rewind` +- Host migration (experimental), bandwidth, test tools: `host-migration/host-migration`, `optimizations`, `testing/debugging` +- GhostObject layer and when to use it: `ghostobject/ghostobject-intro`, `ghostobject-use`, `ghostobject-get-started`, `ghostobject-setup`, `ghostobject-hybrid` +- GhostObject state, input, RPCs, connections, physics: `ghostobject/ghostobject-replicate`, `ghostobject-prediction`, `ghostobject-rpcs`, `ghostobject-connections`, `ghostobject-physics` + +NGO (`com.unity.netcode.gameobjects`): + +- Identity, state, messages: `components/core/networkobject`, `basics/networkvariable`, `advanced-topics/message-system/rpc` +- Transform, animation, physics sync: `components/helper/networktransform`, `components/helper/networkanimator`, `components/helper/networkrigidbody`, `advanced-topics/physics` +- Scenes and topologies: `basics/scenemanagement/scene-management-overview`, `terms-concepts/network-topologies`, `terms-concepts/distributed-authority` +- Latency: `advanced-topics/client-anticipation`, `learn/dealing-with-latency` +- NGO 3.x and hybrid objects (experimental): `upgrade-guide`, `ghostobjects` +- The `netcode.gameobjects` CLI commands: `unity-cli-commands` + +## Glossary + +| Term | Meaning | +|---|---| +| Unity Netcode | `com.unity.netcode` (formerly Netcode for Entities): ghosts with prediction and rollback, authored as GhostObjects or direct ECS ghosts | +| GhostObject layer | `GhostObject`/`GhostBehaviour`/`GhostField`: GameObject authoring over ghosts | +| Direct ECS ghosts | `GhostAuthoringComponent` and `[GhostField]` on ECS components | +| NGO | Netcode for GameObjects: `NetworkObject`/`NetworkBehaviour`/`NetworkVariable`, no rollback-and-replay prediction | + +## Invariants + +1. **Sessions first.** Implement session flows as step 4 routes them. Use the underlying `Lobbies`, `Matchmaker` or `Relay` clients only when the user asks or sessions can't do it, because sessions compose them. +2. **User-facing language.** Describe flows in the user's words (host, join by code); name Lobby, Matchmaker, Relay or Sessions only when the user did. +3. **Choose the stack by requirement** (step 3) and record it with that requirement in the decision record, because later changes must know whether it still holds. +4. **Raw Unity Transport is not a gameplay layer** without an explicit, recorded user requirement, because it leaves replication, prediction and lifecycle to the project. +5. **Recommend, then ask.** State assumptions and recommend a design; ask only decisive questions, in game terms, in the same reply. Block only when every assumption is unsafe. +6. **Ranked or cheat-sensitive play needs a trusted dedicated server**, because player-hosted authority cannot be cheat-safe. +7. **One writer per value.** Clients send requests or inputs; the authority validates and decides, because two writers diverge and cannot be reconciled. +8. **Participant identity comes from the authority.** It assigns slot, team and spawn point on join, not local join or device order. A pre-session choice (character, loadout) is a request carried into the join, such as a session player property, which the authority confirms or reconciles. +9. **Parity with the single-process game is the bar.** Make each feature work across machines, or record it as not yet done, with the reason. +10. **Replicate causes and compact state, not presentation.** Derive animation, VFX, audio and UI locally, because causes carry the information. +11. **Persistent or late-join data is state; one-shot effects are remotes.** Current state, not past events, is the source of truth. +12. **Name platforms by category only** (desktop, mobile, console), never a specific console or platform holder, because those names must not appear in output. + +## Scope + +Voice or text chat belongs to `setup-vivox-voice-chat`; persistence, progression, cloud save, leaderboards, economy, analytics and turn-based or async play belong to `build-live-game`. + +## Workflow + +### 1. Inspect the project + +1. Read `ProjectSettings/ProjectVersion.txt`, `Packages/manifest.json` and `Packages/packages-lock.json`, because the installed versions decide which APIs exist. +2. List multiplayer packages, networking scripts and server build targets. +3. Decide the existing stack from `manifest.json` direct dependencies and the project's scripts (step 1 of [choosing-netcode.md](references/choosing-netcode.md)), not from `packages-lock.json`, because NGO 3.x always pulls in `com.unity.netcode`. +4. For a ghost project, confirm each API and limit you rely on in the installed package source, because they differ between package builds. + +### 2. Determine requirements + +Infer from the conversation, then the project, then ask. A trusted game of at most four players defaults to a listen server with no interview; ask only step 3's responsiveness question, when nothing else decides the stack. + +| Requirement | Decision affected | +|---|---| +| Player count, relevant objects per client | CPU, bandwidth, relevance | +| Cheat risk; who runs the match; hosting budget | Listen server vs dedicated | +| How players join: code, browse, auto-pair | Session APIs | +| Host-loss and reconnect needs | Topology, migration, reconnect | +| Instant own movement on lag; hit registration; physics between players | Stack (prediction, lag compensation), tick rate | +| Existing stack, Rigidbody, Animator or multi-scene content; GameObject or ECS workflow | Stack and rewrite cost | +| Match, persistent or drop-in flow | Scene state, late join | +| Choices made before the game session | Join requests (invariant 8) | +| Desktop, mobile or console | Performance ceiling, prediction CPU cost | + +Propose four budgets rather than asking: players, relevant objects, tick and send rate, per-client bandwidth. + +### 3. Choose authority, topology and netcode stack + +Pick one of each. + +**Stack.** Apply the order in [choosing-netcode.md](references/choosing-netcode.md), then state the stack and the requirement that decided it: +1. Keep the existing stack. +2. Otherwise follow the request: a stack the user names; else prediction, rollback or lag compensation (or instant response on a laggy connection, or fair hits) means Unity Netcode, because NGO has no rollback-and-replay loop. +3. Otherwise apply its requirements table. +4. Otherwise recommend NGO and ask the one responsiveness question in game terms; with no user to ask, decide from clues in the request, and with none, choose NGO. + +**Authority and topology:** + +- Cheat-sensitive or ranked: dedicated, server-authoritative (invariants 6, 7). +- Trusted short game session: client-hosted listen server, because it needs no server hosting. +- Trusted game session that must survive host departure: dedicated authority, because no player's exit ends it; use experimental host migration only if the user explicitly accepts its limits. +- Casual or social game, no dedicated server, must survive host departure, no prediction need: NGO distributed authority, because it has no single host to lose. +- No realtime simulation: no realtime netcode; defer to backend services. + +A client-hosted ghost game defaults to single-world host mode (lowest host cost). GhostObjects support single world only, so binary worlds (host prediction switching, host migration) are for direct ECS ghosts; read `binary-worlds-host-mode` first. State the host mode and why. Tradeoffs: [architecture.md](references/architecture.md). + +### 4. Set up session and connectivity + +Check packages and cloud setup in [workflows-prerequisites.md](references/workflows-prerequisites.md) before coding. Carry the step 3 decision in; don't re-decide it. + +Before you write session code, check that the project is linked to a Unity Cloud project, because sessions and Relay need its project ID. Player sign-in at runtime is separate; it is in the workflow prerequisites. If it is not linked, make the restore point, then follow [link-cloud.md](references/link-cloud.md). + +Create, join and create-or-join, client or dedicated server, use session connectors where [session-connectors.md](references/session-connectors.md) allows. Otherwise: + +| Goal | Session API | +|---|---| +| Create, join by code | `CreateSessionAsync`, `JoinSessionByCodeAsync` | +| Browse open games | `QuerySessionsAsync` on indexed session properties | +| Quick join | `MatchmakeSessionAsync` + `QuickJoinOptions`; set `CreateSession` to create when nothing matches; no `Timeout` unless asked | +| Queue matchmaking | `MatchmakeSessionAsync` + `MatchmakerOptions` and a deployed queue | +| Dedicated server, backfill | `MultiplayerServerService.Instance` under `UNITY_SERVER`; `WithBackfillingConfiguration` | +| Host migration (only if step 3 chose it), reconnect | `WithHostMigration`; `ReconnectToSessionAsync` | +| Connectivity | `WithRelayNetwork` across home networks, `WithDirectNetwork` for published addresses | + +APIs and options: [entrypoints.md](references/entrypoints.md); server rows: [dgs-entrypoint.md](references/dgs-entrypoint.md). Phrase user questions per [implementation-fit.md](references/implementation-fit.md) and [examples.md](references/examples.md). Use [underlying-services.md](references/underlying-services.md) only as invariant 1 allows. + +Pick one owner of netcode start-up per game session, because two starters duplicate worlds. The default network handler (`WithRelayNetwork`/`WithDirectNetwork`) connects or listens, and starts NGO whenever `com.unity.netcode.gameobjects` is installed, otherwise Unity Netcode (never on WebGL): + +| Stack | Who starts it | Don't | +|---|---|---| +| NGO | The default handler | Call `NetworkManager` `StartHost`/`StartClient`, or leave Unity Netcode's bootstrap on, because NGO 3.x installs it and it can take port 7979 | +| Direct ECS ghosts | The default handler | Call `Netcode.Connect`/`StartAsHost`, leave the automatic bootstrap on, or leave `ClientServerBootstrap.AutoConnectPort` above 0, because the handler reuses bootstrap worlds and fails on a client world that auto-connected | +| GhostObject | You, with `Netcode.StartAsHost` (for Relay, see netcode-lifecycle.md); the session only supplies membership and connection details | Host through the default handler (it creates separate client and server worlds), or install NGO (its handler runs instead) | + +If the installed packages' docs don't confirm the default handler for your stack, or packages aren't installed yet, start the stack yourself and say so. A custom `INetworkHandler` owns start-up itself. With no network option, the host starts the session network later (`session-networking`). + +### 5. Choose authoring + +- NGO: registered `NetworkObject` prefabs, `NetworkVariable` for state, RPCs for one-shot requests. Read the NGO pages first. +- Unity Netcode: read [ghost-authoring.md](references/ghost-authoring.md). A GameObject project uses GhostObject; an ECS-native or maximum-scale one uses direct ECS ghosts. **Declare every `GhostBehaviour` in its own file named after the class**, because a second class in a shared file saves onto the prefab as a missing script without warning. Never name a namespace segment `Netcode`, because it hides the `Netcode` facade in other files too. +- Existing NGO game that now needs prediction: keep stable systems; move only the subsystems that need prediction to ghosts, across clear authority and state boundaries (*NGO upgrade path* in [architecture.md](references/architecture.md)). Read NGO's `ghostobjects` page before proposing experimental hybrid objects. + +### 6. Design replication + +For every gameplay state, decide: writer; input or request sent; replicated state; predicted or interpolated (NGO: interpolated or anticipated only); local presentation; relevance and send rate; spawn, despawn, owner-drop, late-join and reconnect behavior. + +Before writing GhostObject code, apply *GameObject-layer rules* in [netcode-lifecycle.md](references/netcode-lifecycle.md). Ghost rules in [syncing-gameplay.md](references/syncing-gameplay.md) and netcode-lifecycle.md are for Unity Netcode only; invariants 7, 8, 10 and 11 hold for NGO too. + +### 7. Integrate and verify + +1. Before writing gameplay networking code, satisfy the implementation gate in [verification-gate.md](references/verification-gate.md). +2. Confirm zero console errors with `unity command console status`. +3. For implementation work, verify in one Multiplayer Play Mode scenario per [multiplayer-play-mode.md](references/multiplayer-play-mode.md): the main Editor hosts and a virtual player joins, because a virtual player is a separate process and proves replication without a build. This includes games whose rules run in backend services: give each player its own instance, not two identities in one process. Run `unity command` first to list the installed packages' command groups. Then, reading state with commands, not logging or screenshots: + 1. Before `start_scenario`, run the stack's `audit` and fix what it reports, because clones must not receive its project writes. + 2. Drive input on each instance (the host and the clone) with `script eval` calls to the game's own methods (move each player, trigger the core gameplay event), let gameplay advance, then confirm the result on both instances with `netcode.ghost get` or `netcode.gameobjects list_objects` (NGO `NetworkVariable` values: `script eval`), because unchanging state proves the connection, not the gameplay. + 3. Repeat with lag set on the clone by `netcode.simulator set` (NGO: `netcode.gameobjects.simulator set`), because prediction and smoothing problems only show under latency. +4. Build players only for the gate's final-testing step, or when MPPM can't launch a clone, because builds are slow to iterate on. +5. Netcode work is done only when the gate's completion check passes on that cross-process evidence. Session-only work is done when the gate's session create, join and read-back evidence exists. Diagnosis stops at zero console errors unless the user asked for proof or you suspect a specific fault; then enter Play mode once to chase it, reading the world through `script eval`, no logging or screenshots. +6. If it fails, reread the docs and the matching reference before another fix. + +## Example + +Request: "GameObject project. Four friends, trusted co-op party game, join with a code." No stack is installed and nothing needs prediction, so: listen server, no interview, NGO with `NetworkVariable` state, and Host and Join session connectors on Relay. The report ends "Tell me if your own character must react instantly on a laggy connection, or if the host may leave mid-match". + +Counter-example: "Online arena shooter; players say shots miss on high ping." Hit registration needs lag compensation, so Unity Netcode on a dedicated server; the report says NGO was ruled out for lacking rollback and server-side rewind. + +## Reference map + +| Task | Read | +|---|---| +| Topology, host mode, NGO migration | [architecture.md](references/architecture.md) | +| NGO vs Unity Netcode, rewrite cost | [choosing-netcode.md](references/choosing-netcode.md) | +| GhostObject vs direct ECS | [ghost-authoring.md](references/ghost-authoring.md) | +| State, input, prediction, remotes, physics, animation | [syncing-gameplay.md](references/syncing-gameplay.md) | +| Connect, worlds, spawn, scenes, rejoin, triage, error strings | [netcode-lifecycle.md](references/netcode-lifecycle.md) | +| Direct ECS ghosts, rollback, relevance | [netcode-for-entities.md](references/netcode-for-entities.md) | +| Lag, bandwidth, budgets, profiling | [performance-and-scale.md](references/performance-and-scale.md) | +| Implementation gate and completion check | [verification-gate.md](references/verification-gate.md) | +| Host + client or dedicated-server verification in MPPM | [multiplayer-play-mode.md](references/multiplayer-play-mode.md) | + +## Final report + +Use this unless the request is narrower: + +```text +Assumptions: +Package state: +Recommendation: + + , with the requirement that decided each +Session flow: +Replication: +Lifecycle: +Risks: +Verification: +Side effects: +Follow-ups for you: +Tell me if differs and I will revise this. +``` diff --git a/skills/build-multiplayer-game/references/architecture.md b/skills/build-multiplayer-game/references/architecture.md new file mode 100644 index 0000000..3a74688 --- /dev/null +++ b/skills/build-multiplayer-game/references/architecture.md @@ -0,0 +1,171 @@ +# Architecture + +## Contents + +- [Ghost runtime and authoring](#ghost-runtime-and-authoring) +- [Authority](#authority) +- [Client-host modes](#client-host-modes) +- [Practical recommendations](#practical-recommendations) +- [NGO upgrade path](#ngo-upgrade-path) +- [Requirement conflicts](#requirement-conflicts) + +Use this reference for authoring, authority, host topology, and moving Netcode for +GameObjects (NGO) subsystems to ghosts when they need prediction. Make the NGO versus +Unity Netcode choice first, in workflow step 3. + +Links in this file resolve to the skill directory's `references/` folder, the folder this file is in. Project and package paths in code spans are relative to the user's project or the package root. + +## Ghost runtime and authoring + +`com.unity.netcode` is the runtime for games that need prediction, rollback, lag +compensation or high scale. It has two authoring surfaces on one replication +pipeline: GhostObject for GameObject/MonoBehaviour teams and direct ECS ghosts for +ECS-native teams or the highest scale. Read the Netcode `ghostobject/ghostobject-intro` +page for the GhostObject building blocks and the `ghostobject/ghostobject-use` page to +choose between the surfaces. Use NGO (`NetworkObject`, `NetworkBehaviour`, +`NetworkVariable`, RPCs) instead for a GameObject game with no prediction, rollback or +lag-compensation need, for distributed authority, or for an existing NGO project. + +Confirm each GameObject-layer API in the installed `com.unity.netcode` source +(`Runtime/GameObjectLayer/`) before relying on it. + +## Authority + +Choose dedicated server or client-hosted with the Netcode `choose-network-topology` +page: dedicated for ranked, competitive or cheat-sensitive play; client-hosted for +trusted small sessions, which then need a host-loss design. Turn-based or async +gameplay needs no realtime netcode, because a backend owns canonical state. + +Server authority still requires validation. Clients submit input or requests; +the authority checks ownership, rate, range, resources, and game rules. A server +that accepts client-reported outcomes is not secure. + +## Client-host modes + +Two listen-server arrangements exist; single world is the default. Which one a host +gets depends on what starts it: the automatic bootstrap reads **Host World Mode +Selection** on `NetcodeConfig`; `Netcode.StartAsHost` uses its `hostWorldMode` +argument (default single world); the Multiplayer Services default handler creates +separate client and server worlds when none exist. GhostObjects support single world +only (Netcode `ghostobject/ghostobject-connections` page), so binary worlds are for +direct ECS ghosts. + +Use single world for a client-hosted ghost game. Before choosing binary worlds for a +direct ECS game, compare the modes on the Netcode `choose-network-topology` page and +the *Limitations and considerations* section of the `single-world-host-mode` page. +A single-world host can't simulate lag on its own objects, so test latency from a +second process; a Multiplayer Play Mode clone counts. + +Binary-worlds host (direct ECS ghosts only, because GhostObjects don't support +binary worlds): the host process holds the authoritative server-world ghost and its +client-world replica. Draw presentation only from the client world, or the host +renders everything twice, visible as a second, trailing object because the replica +is interpolated. + +That remedy doesn't apply to a single-world host, which has no replica. Host +duplicates happen in both modes for different reasons — read the single-world +consequences below before concluding that doubled geometry on a host does not +apply to your mode. + +### Single-world details + +- Both client and server roles are true in the host world (Netcode + `single-world-host-mode` page). Almost every single-world host defect follows + from that one fact, so the consequences are spelled out here and the rest of the + skill links back to this list. +- The host's own connection is synthetic (the same page describes it). It raises + no connection events and is absent from + `NetcodeWorld.AllConnections`. Player counting that was correct on a + binary-worlds server (internal IPC client + remotes) undercounts by one on a + single-world host — count the host explicitly when its local connection is + missing from the list. +- All host ghosts are authoritative, and the client receive/spawn/update pipeline + early-outs on `IsHost()`. There is **no local replica** in this mode — so a + doubled object on a single-world host is *application-created*, not a replica. + For transform presentation, set **Full Tick Smoothing** to `Interpolate` on the ghost + prefab (`BaseGhostSettings.FullTickSmoothing`), because it defaults to + disabled; smooth other visual values separately. +- **`ServerToClient` remotes are delivered to the host itself.** A remote method + body executes on the receiving *role*, and on a single-world host both roles are + the same process and world, so the call dispatches into the host's own handler + (a local passthrough that skips serialization; read the same page before writing + a custom RPC serializer). + Any handler with a visible or stateful side effect (spawning a visual proxy, + playing a one-shot, applying damage, deforming terrain) must be idempotent with + the authoritative path or skip its mirror work when `IsServer` is also true. A handler that *mirrors* an + authoritative action into local presentation draws two overlapping objects on + the host while remote clients see one. +- **`IsServer` and `IsClient` are both true here.** An `if (IsServer) … else …` + pair takes only the server branch on the host, so host-side client work never + runs. Write independent `if (IsServer)` and `if (IsClient)` blocks so the host + runs both (Netcode `ghostobject/ghostobject-prediction` page), and test as a host + as well as a dedicated server. +- **`CanWriteState` is true on the host** for interpolated-only ghosts as well as + predicted ones, because the server retains `PredictedGhost`. Convenient for + authoritative writes, and another reason mirror code needs its own guard. +- **The host is never replayed.** The rollback systems and the prediction history + system early-out on `IsHost()` and the prediction group runs once per tick, so a + single-world host always takes the authority branch. Client-only prediction + defects — compounding deltas, missing reconciliation, non-idempotent replay — + are structurally unreachable in one process, and host-side profiling understates + prediction cost. Prediction correctness requires a second process; see + *Verifying prediction* in the performance reference. +- Client systems see every player's input in the combined world; filter host-local + input with `GhostOwnerIsLocal` as the same page describes. + +## Practical recommendations + +| Game profile | Recommendation | +| --- | --- | +| Two-to-four-player trusted co-op or party game, no responsiveness need | NGO + listen server | +| Two-to-four-player trusted action co-op that needs instant own-movement | GhostObject + single-world host; direct ECS ghosts if it needs binary-worlds features | +| Casual or social game that must survive host departure, no dedicated server | NGO distributed authority | +| Co-op that must survive host departure and needs prediction | Dedicated authority, or experimental host migration on direct ECS ghosts with a binary-worlds host (Netcode `binary-worlds-host-mode` page) after accepting its limitations; not available to GhostObjects | +| Competitive action | Dedicated server + direct ECS ghosts or verified GhostObject authoring | +| Existing GameObject game adding multiplayer | NGO, unless it needs prediction; then GhostObject, with the rewrite cost stated | +| Existing NGO game | Keep stable NGO code; migrate measured bottlenecks or new bounded systems | +| Large entity-heavy simulation | Direct ECS ghosts + dedicated server + relevance/importance | +| Turn-based/async | Backend state; no realtime netcode unless presentation truly needs it | + +## NGO upgrade path + +Use this when an NGO game later needs prediction, rollback or lag compensation in +part of its gameplay. Treat migration as a sequence of bounded system replacements, +not a rewrite: + +1. Profile and select a subsystem that benefits from prediction, rollback, + snapshot compression, relevance, or high object counts. +2. Define its one authority and canonical state independently of either API. +3. Map NGO identity, ownership, state, RPCs, spawn/despawn, references, scenes, + and reconnect behavior to the ghost design. +4. Move a complete boundary such as movement, vehicles, projectiles, or a class + of replicated actors. Never let NGO and ghosts write the same state. +5. Both packages use the `Unity.Netcode` namespace; in a project with both, qualify + ambiguous types and keep each stack in its own assembly. NGO 3.x can also put a + `NetworkObject` and a GhostObject on one prefab (a hybrid object): NGO then drives + the connection through a single-world Netcode world, and only the transform, + Rigidbody and GhostBehaviour state are snapshot-replicated and predicted; + `NetworkVariable`s and RPCs are not rolled back. That integration is experimental, + needs `HostWorldModeSelection` set to single world, and excludes distributed + authority, in-scene placed objects, pooling and client-authoritative motion. Read + NGO's `ghostobjects` and `upgrade-guide` pages before proposing it, and test + interoperation in the installed build. +6. Retain NGO where it still meets the need. Remove it only after no retained + system depends on it. + +Good migration candidates have measurable network/CPU cost or need prediction. +Low-frequency UI/game-session glue is usually not worth moving first. + +## Requirement conflicts + +| Conflict | Resolution | +| --- | --- | +| Cheat-safe + no server cost | Fund dedicated authority for protected modes, or drop the cheat-safe claim | +| Host must leave + single-world/listen host | Prefer dedicated authority; host migration is experimental, best-effort, and documented for binary-worlds hosts only, so not for GhostObjects | +| Dedicated parity + minimum host overhead | Choose binary parity or single-world efficiency; they are different code paths | +| Hundreds of relevant objects + no relevance work | Reduce scope or implement relevance/importance and measure | +| Twitch physics + weak client hardware | Narrow predicted bodies, lower rate, or relax responsiveness | +| Persistent world + player-hosted only | Add a canonical backend/server or abandon persistence guarantees | + +Identify which of security, cost, latency, or scope cannot move, then state the +tradeoff rather than promising incompatible requirements. diff --git a/skills/build-multiplayer-game/references/choosing-netcode.md b/skills/build-multiplayer-game/references/choosing-netcode.md new file mode 100644 index 0000000..08c25ea --- /dev/null +++ b/skills/build-multiplayer-game/references/choosing-netcode.md @@ -0,0 +1,44 @@ +# Choosing the netcode stack + +Links in this file resolve to the skill directory's `references/` folder, the folder this file is in. Project and package paths in code spans are relative to the user's project or the package root. + +Two stacks sync gameplay. Pick one per project, or per bounded subsystem in an existing project, before choosing authoring or writing code. + +- **NGO** (`com.unity.netcode.gameobjects`): `NetworkObject`, `NetworkBehaviour`, `NetworkVariable`, RPCs. State changes replicate from the authority, and remote copies interpolate. +- **Unity Netcode** (`com.unity.netcode`): ghosts with snapshot delta compression, client prediction and rollback, lag compensation, importance and relevance. It has two authoring layers, GhostObject and direct ECS; see [ghost-authoring.md](ghost-authoring.md). GhostObjects support single-world hosts only. If the installed package has no public `GhostObject` type, use direct ECS ghosts (see the fallback order in ghost-authoring.md). + +NGO 3.x depends on `com.unity.netcode` and installs it with the Entities packages, so read NGO's `package.json` for the minimum Editor (keep NGO 2.x on older Editors) and target platforms that support Burst and Entities (NGO `upgrade-guide` page). A project that only uses NGO therefore still resolves `com.unity.netcode`; that is not a ghost project. Turn that package's automatic bootstrap off in an NGO project (`netcode.config set --field enable_client_server_bootstrap --value DisableAutomaticBootstrap`), because otherwise it can create Unity Netcode worlds on port 7979 in every process, MPPM clones included, and an NGO client's join then fails. + +NGO has no rollback-and-replay prediction loop and no server-side rewind. Before recommending NGO for anything latency-sensitive, read its `advanced-topics/client-anticipation` and `learn/dealing-with-latency` pages, because they state what NGO leaves for the project to build. + +## Decide in this order + +1. **Existing stack.** Decide it from the direct dependencies in `manifest.json` and the project's assets and scripts (`NetworkManager`/`NetworkObject` versus `GhostObject`/`GhostAuthoringComponent`), not from `packages-lock.json`. Keep that stack for new work, because both stacks use the `Unity.Netcode` namespace and two parallel net models double the lifecycle and test cost. To move an NGO subsystem that now needs prediction, follow *NGO upgrade path* in [architecture.md](architecture.md). NGO 3.x hybrid objects (a `NetworkObject` and a GhostObject on one prefab) are experimental, need a single-world host, and exclude distributed authority, in-scene placement, pooling and client-authoritative motion; read NGO's `ghostobjects` page before proposing them. +2. **Explicit request.** If the user names a stack, use it. If they ask for prediction, rollback, reconciliation, lag compensation or instant own-movement on a laggy connection, use Unity Netcode, because NGO cannot provide these without the project building them. +3. **Requirements table.** Otherwise, apply the first row below that the game matches. +4. **Ask.** If no row matches, recommend NGO and ask one question in game terms, in the same reply: "Should your own character react instantly even on a laggy connection, or is a short delay fine?". "Instantly" means Unity Netcode. +5. **Cannot ask.** In a run with no user to answer, decide from clues in the request (genre, "physics", "hundreds of units", "competitive", "party game"). If nothing points either way, choose NGO. + +| The game needs | Stack | Why | +|---|---|---| +| Competitive or twitch action: shooter, fighting, racing with contact | Unity Netcode, dedicated server | Hit registration and responsive input need prediction and lag compensation | +| Server-side hit rewind | Unity Netcode | NGO has no rewind implementation; Netcode's `server-rewind` page covers it | +| Predicted physics between players (pushing, vehicles colliding) | Unity Netcode | NGO simulates physics only on the authority; other instances are kinematic, and no rollback corrects them | +| Many relevant objects or players, or a tight bandwidth budget | Unity Netcode | Delta-compressed snapshots, importance and relevance are built in | +| ECS-native project or team | Unity Netcode, direct ECS | Matches the existing workflow | +| No dedicated server, the match must survive the host leaving, casual or social play | NGO, distributed authority | Distributed authority exists only in NGO; its docs say it does not suit competitive games that need a predictive motion model | +| Existing GameObject game with significant Rigidbody, Animator or multi-scene content, and no prediction need | NGO | NGO's network components cover that content as is; Unity Netcode means converting to Unity Physics or accepting GhostObject's limits (Netcode `ghostobject/` pages) | +| Low-end mobile CPU budget with simple gameplay | NGO | Prediction re-simulates several ticks per frame and multiplies CPU cost | +| Trusted co-op or party game, a few players, no responsiveness requirement | NGO, listen server | Least code and setup for the need | +| Turn-based or async play | Neither | Hand off to `build-live-game` | + +## Cost of choosing Unity Netcode for existing content + +When Unity Netcode wins for an existing GameObject game, report the rewrite cost under Risks, because the user is trading content they already have for prediction: + +- Direct ECS predicted physics runs on Unity Physics (`com.unity.physics`), not the GameObject physics engine. `Rigidbody`, `Collider` and joint setups are converted and re-tuned. Read the Netcode `physics` page for its limits before promising parity. +- GhostObject keeps GameObject physics but replays the whole default physics scene on every predicted tick, so existing client-only physics such as debris moves to a separate physics scene. Count that move in the rewrite cost. Read the Netcode `ghostobject/ghostobject-physics` page, and the installed package source, for setup and limits before promising parity. + +## Record the choice + +Write the chosen stack and the requirement that decided it in the decision record (README or `NETWORKING.md`), with the installed package version. A later change can then tell whether that requirement still holds before it adds or moves systems. diff --git a/skills/setup-multiplayer-services/references/dgs-entrypoint.md b/skills/build-multiplayer-game/references/dgs-entrypoint.md similarity index 56% rename from skills/setup-multiplayer-services/references/dgs-entrypoint.md rename to skills/build-multiplayer-game/references/dgs-entrypoint.md index 9b10c66..1e34151 100644 --- a/skills/setup-multiplayer-services/references/dgs-entrypoint.md +++ b/skills/build-multiplayer-game/references/dgs-entrypoint.md @@ -1,9 +1,13 @@ -## Table of Contents +# Dedicated game server entrypoint + +## Contents + +Links in this file resolve to the skill directory's `references/` folder, the folder this file is in. Project and package paths in code spans are relative to the user's project or the package root. - [Overview](#overview) - [Build and assembly constraints](#build-and-assembly-constraints-unity_server) - [`IMultiplayerServerService` capabilities](#imultiplayerserverservice-capabilities) -- [Method signatures](#method-signatures) +- [API reference](#api-reference) - [Matchmaker server extensions](#matchmaker-server-extensions-matchmakerserverextensions) - [Session options (shared types)](#session-options-shared-types) - [Errors](#errors) @@ -29,7 +33,7 @@ Any **game or tool code** that references **`Unity.Services.Multiplayer.Server`* | **Scripting define** | Wrap references (types, calls, `using` that pulls server-only APIs) in **`#if UNITY_SERVER`** … **`#endif`** (or a define that implies the same server build), so non-server targets do not compile that code. | | **Assembly Definition** | In the **`.asmdef`** of the assembly that references **`Unity.Services.Multiplayer.Server`**, set **`defineConstraints`** to include **`UNITY_SERVER`** so the dependent assembly is not built for client-only targets. | -Use one or both so client/player builds never require the Server assembly to be present or linked incorrectly. +Default to `#if UNITY_SERVER` around the calls. Use the assembly definition instead when a whole assembly is server-only, because then no `#if` is needed in its files. Either way, client and player builds must not need the Server assembly. ## `IMultiplayerServerService` capabilities @@ -41,34 +45,15 @@ Use one or both so client/player builds never require the Server assembly to be > **`GetSessionAsync`** exists on **`IMultiplayerServerService`** for package-internal use and is **`internal`** in the SDK source; treat the three **`Create*`** methods above as the supported public server entry surface for session creation from game code. -## Method signatures - -```csharp -// Creates a new dedicated-server session. Returns IServerSession. Throws SessionException on failure. -Task CreateSessionAsync(SessionOptions sessionOptions) - -// Creates or joins a server session using an explicit session id. -Task CreateSessionAsync(string sessionId, SessionOptions sessionOptions) +## API reference -// Creates a server session from a Matchmaker match id and session options. -Task CreateMatchSessionAsync(string matchId, SessionOptions sessionOptions) -``` +The three `Create*` methods above take `SessionOptions` and return `IServerSession`. Read [game server hosting support](https://docs.unity.com/en-us/mps-sdk/game-server-hosting-support.md) before writing server code, and the [Multiplayer Services package scripting API](https://docs.unity3d.com/Packages/com.unity.services.multiplayer@) for exact signatures. ## Matchmaker server extensions (`MatchmakerServerExtensions`) All members below are declared in **`Unity.Services.Multiplayer.Server`** (`MatchmakerServerExtensions`). -```csharp -// Configure backfill behavior on SessionOptions before create/match session. -T WithBackfillingConfiguration(this T options, bool enable, bool automaticallyRemovePlayers, - bool autoStart, int playerConnectionTimeout, int backfillingLoopInterval) where T : SessionOptions - -// Start backfilling on a matchmade session (server / session handle). -Task StartBackfillingAsync(this ISession session) - -// Stop backfilling on a matchmade session. -Task StopBackfillingAsync(this ISession session) -``` +`WithBackfillingConfiguration` on `SessionOptions` configures backfill before create or match session, and `StartBackfillingAsync` / `StopBackfillingAsync` on a matchmade `ISession` control it. Read [Matchmaker backfill](https://docs.unity.com/en-us/mps-sdk/matchmaking/mm-backfill.md) for the parameters. ## Session options (shared types) @@ -76,4 +61,13 @@ Task StopBackfillingAsync(this ISession session) ## Errors -Async methods on **`IMultiplayerServerService`** throw **`SessionException`** on failure (same family as the client **`IMultiplayerService`** session APIs). +Async methods on `IMultiplayerServerService` throw `SessionException` on failure, the same as the client session APIs. Read `SessionException`'s `SessionError` value, then resolve it: + +| `SessionError` | Root cause | Resolution | +| --- | --- | --- | +| `InvalidParameter` | A parameter is missing or malformed, for example `SessionOptions.MaxPlayers` left at `0` or an empty match id | 1. Print the options and match id you passed. 2. Set `MaxPlayers` above 0 and pass the match id from the allocation unchanged. 3. Retry. | +| `NotAuthorized` or `Forbidden` | The server is not signed in, or its credentials lack permission for the project or environment | 1. Confirm Unity Services initialized and the server signed in with a service account (`ServerAuthenticationService.Instance.SignInWithServiceAccountAsync`) before the call; backfill also needs the service account to have the Matchmaker Backfill Admin role. 2. Check the server's project and environment match the matchmaker's. 3. Retry. | +| `SessionNotFound` or `AllocationNotFound` | The match id does not name a live allocation, often because it expired or came from another environment | 1. Log the match id the server received. 2. Create the match session as soon as the allocation arrives. 3. If it still fails, rerun the matchmaking flow and use the new id. | +| `RateLimitExceeded` | Too many session calls in a short time | 1. Remove retry loops without a delay. 2. Back off and retry once. | + +For other values, read the `lobby-error-messages` page in the Multiplayer Services docs. diff --git a/skills/build-multiplayer-game/references/entrypoints.md b/skills/build-multiplayer-game/references/entrypoints.md new file mode 100644 index 0000000..e7fd978 --- /dev/null +++ b/skills/build-multiplayer-game/references/entrypoints.md @@ -0,0 +1,20 @@ +# Session API entrypoints + +Links in this file resolve to the skill directory's `references/` folder, the folder this file is in. Project and package paths in code spans are relative to the user's project or the package root. + +Implement session flows against `MultiplayerService.Instance` and `ISession` (cast to `IHostSession` when hosting). Read the page for the call you're writing before using it, because defaults and limits change between package versions: + +- [Create a session](https://docs.unity.com/en-us/mps-sdk/create-session.md) and [session configuration options](https://docs.unity.com/en-us/mps-sdk/config-options.md): `SessionOptions`, properties, visibility, indexed properties for queries. +- [Find and join a session](https://docs.unity.com/en-us/mps-sdk/join-session.md): join by id or code, `QuerySessionsAsync` filters and sorting, reconnect. +- [Matchmaking](https://docs.unity.com/en-us/mps-sdk/matchmake-session.md) and [Quick Join](https://docs.unity.com/en-us/mps-sdk/matchmake-lobby.md): `MatchmakerOptions`, `QuickJoinOptions`. +- [Session networking](https://docs.unity.com/en-us/mps-sdk/session-networking.md) and [manage the session network connection](https://docs.unity.com/en-us/mps-sdk/manage-session-network-connection.md): `WithRelayNetwork`, `WithDirectNetwork`, starting the network later from the host, custom `INetworkHandler`. +- [Host migration](https://docs.unity.com/en-us/mps-sdk/session-host-migration.md), [Session observer](https://docs.unity.com/en-us/mps-sdk/session-observer.md), [ScriptableObject sessions](https://docs.unity.com/en-us/mps-sdk/scriptableobject-sessions.md) (`MultiplayerSession`, `SessionConnector`), and [error messages](https://docs.unity.com/en-us/mps-sdk/lobby-error-messages.md) (`SessionException`, `SessionError`). +- The [Multiplayer Services scripting API](https://docs.unity3d.com/Packages/com.unity.services.multiplayer@) for exact signatures. + +Rules the docs don't give, or that models get wrong: + +- Set `SessionOptions.MaxPlayers` above 0 when creating a session, because the default of 0 is rejected. +- Leave `QuickJoinOptions.Timeout` unset unless the user asked for one, because an unrequested timeout changes how long quick join retries. +- Use `WithDistributedAuthorityNetwork()` only when the chosen stack is NGO and the topology is distributed authority, because distributed authority exists only in NGO. +- `WithNetworkHandler(INetworkHandler)` replaces the default netcode integration, so the custom handler owns netcode start-up itself. +- Who starts netcode with the default handler is decided in SKILL step 4; world creation and connect details are in [netcode-lifecycle.md](netcode-lifecycle.md). diff --git a/skills/setup-multiplayer-services/references/examples.md b/skills/build-multiplayer-game/references/examples.md similarity index 80% rename from skills/setup-multiplayer-services/references/examples.md rename to skills/build-multiplayer-game/references/examples.md index ba5e38a..f46b643 100644 --- a/skills/setup-multiplayer-services/references/examples.md +++ b/skills/build-multiplayer-game/references/examples.md @@ -1,8 +1,8 @@ -## Examples: user-facing language +# Examples: user-facing language -These illustrate **User-facing questions and explanations** in the implementation-fit reference. They are for prose to the user, not for code or file edits (those may use real API names). +These illustrate the user-facing language rules. They are for prose to the user, not for code or file edits (those may use real API names). -### Clarifying questions +## Clarifying questions **Bad (SDK / product vocabulary):** @@ -16,7 +16,7 @@ These illustrate **User-facing questions and explanations** in the implementatio - "Should matchmaking be **automatic** (the game finds opponents for you) or **manual** (players choose a room)?" - "When two players are on different home networks, is **mediated connectivity** (no open ports on a router) a requirement?" -### Explanations and plans +## Explanations and plans **Bad (splitting named backend products):** @@ -28,6 +28,6 @@ These illustrate **User-facing questions and explanations** in the implementatio - "We'll keep **room metadata** (map, rules) in one place, use **brokered connectivity** when direct links are unreliable, and **automatic pairing** for ranked." - "The **main multiplayer package API** can own **room state and joins** so you don't add a second room system on top." -### When the user already named a product +## When the user already named a product If they wrote e.g. "we're on **Relay** already," you may **mirror their wording** in discussion; still avoid **extra** product enumeration they did not ask for. diff --git a/skills/build-multiplayer-game/references/ghost-authoring.md b/skills/build-multiplayer-game/references/ghost-authoring.md new file mode 100644 index 0000000..187d62f --- /dev/null +++ b/skills/build-multiplayer-game/references/ghost-authoring.md @@ -0,0 +1,19 @@ +# Ghost authoring + +Links in this file resolve to the skill directory's `references/` folder, the folder this file is in. Project and package paths in code spans are relative to the user's project or the package root. + +Read this file only after workflow step 3 selected Unity Netcode. It picks the authoring layer. Read *Choose the right approach* on the Netcode `ghostobject/ghostobject-use` page first: both layers share one replication pipeline and can be combined. + +## Fallback order (new projects) + +1. `GhostObject`/`GhostBehaviour` for a GameObject project. +2. Direct ECS ghosts for an ECS-native project, or when the package has no GameObject layer, the bridge has a reproduced defect, or it cannot express a required system. + +## A step down needs evidence + +Moving a GameObject project from GhostObject to direct ECS needs a reproduced defect or a named missing API, because direct ECS changes the team's whole workflow. Record which one in the decision record. + +## Before you design + +- Scene-placed ghosts, hierarchy or predicted Rigidbody: read the installed package's `Documentation~/ghostobject/` pages (`ghostobject-replicate`, `ghostobject-prediction`, `ghostobject-physics`) for the current limits, because they differ between package builds. +- Existing NGO game moving a subsystem: read *NGO upgrade path* in [architecture.md](architecture.md). diff --git a/skills/build-multiplayer-game/references/implementation-fit.md b/skills/build-multiplayer-game/references/implementation-fit.md new file mode 100644 index 0000000..a52c65b --- /dev/null +++ b/skills/build-multiplayer-game/references/implementation-fit.md @@ -0,0 +1,28 @@ +# Implementation fit: clarify multiplayer requirements + +Links in this file resolve to the skill directory's `references/` folder, the folder this file is in. Project and package paths in code spans are relative to the user's project or the package root. + +Ground advice in the choices that fit *this* application before recommending architecture or APIs, and map answers to [entrypoints.md](entrypoints.md) only once requirements are clear. Topology and authority decisions live in the architecture reference; this file covers how to obtain requirements and how to phrase questions. Phrasing samples: [examples.md](examples.md). + +**How to obtain requirements (in order):** + +1. **Conversation and task context.** Use stated goals (e.g. "2-player co-op", "ranked 5v5", "mobile", "host leaves often"). +2. **Project state.** Inspect the workspace (`Packages/manifest.json` for multiplayer packages, existing networking scripts, platform settings) and align with what is already chosen. +3. **Ask the user.** If a dimension below would **change** the recommendation and is not inferable from (1) or (2), ask a **short, targeted** question in the same reply as the recommendation, with your assumption stated, instead of blocking on the answer. Follow the language rules below. + +## User-facing questions and explanations + +- **Clarifying questions** stay **high level**: player count, how people **find or join** a game, who **runs** the match (one player's machine vs a dedicated machine), fairness and latency expectations, disconnect/reconnect and "host leaves" behavior, target platforms, and which **Unity networking stack** the project already uses **only if** the user brought it up or it is visible in the project. Phrase questions in **game / product** terms. +- **Do not** name or ask about Unity **product or service** implementations in questions: avoid the terms **Sessions**, **Lobby**, **Matchmaker**, **Relay**, and avoid **API or type names** (`ISession`, `QuerySessionsAsync`). The user should not need SDK vocabulary to answer. +- In **explanations, summaries, and plans** addressed to the user (outside code blocks and file edits), **do not mention** Lobby, Matchmaker, Relay, or Multiplayer **Sessions** as named products, and do not contrast or enumerate those underlying services, unless the **user** asked about them by name or asked for that level of detail. Use plain language ("list of open games", "automatic pairing", "brokered connectivity when direct player-to-player links are unreliable", "the main Unity multiplayer package API"). +- **Code, API references, and file contents** use the exact types, namespaces, and methods. + +## Dimensions to consider + +- **Player count and scale.** Players per match; many small matches vs few large ones. Topology choice: architecture reference. +- **Competitive stakes.** Tolerance for host-based authority vs need for strict authority and fairness. +- **Discovery and how matches form.** Join codes or invites vs **browsing a list** of open games vs **automatic pairing**; visibility and filterable game metadata. *Internal mapping:* query/list flows, quick-join filters, ticket/queue flows; session properties and indexes. +- **Connection model and resilience.** **NAT / home networks** (mediated connectivity vs published listen addresses), **reconnect** after disconnects, and whether the match must survive the host leaving. *Internal mapping:* relay vs direct network options, `ReconnectAsync`, host migration hooks. +- **Platform constraints.** Targets (e.g. **mobile** dropouts and backgrounding, **console** networking expectations) that affect match lifetime, reconnect UX, and viable connection patterns. +- **Responsiveness.** Whether a player's own actions must react instantly even on a laggy connection, and whether hits must register fairly at high ping. Ask it as "Should your own character react instantly even on a laggy connection, or is a short delay fine?" *Internal mapping:* instant means prediction and lag compensation, so Unity Netcode; a short delay is fine means NGO ([choosing-netcode.md](choosing-netcode.md)). +- **Team skills and codebase stack.** An existing project extends the stack already in `manifest.json` rather than adding a parallel net model. A new project picks its stack by the requirements in [choosing-netcode.md](choosing-netcode.md); team familiarity with GameObjects or ECS breaks a tie. diff --git a/skills/build-multiplayer-game/references/link-cloud.md b/skills/build-multiplayer-game/references/link-cloud.md new file mode 100644 index 0000000..13bca79 --- /dev/null +++ b/skills/build-multiplayer-game/references/link-cloud.md @@ -0,0 +1,12 @@ +# Link the Project to Unity Cloud + +Sessions, Relay and matchmaking need a linked Unity Cloud project ID. Linking writes `ProjectSettings/ProjectSettings.asset`: do it only when the task needs those calls or asks to link, after the restore point. Pass `--project-path ` to every `unity command` below, because without it the CLI drives the Editor of the shell's current folder, which may be another project. + +1. A non-empty `cloudProjectId` in `ProjectSettings/ProjectSettings.asset` means it is linked: skip the rest. +2. Ask the user before linking. Run `unity auth status`; if it reports signed out, run `unity auth login` and ask the user to finish signing in in the browser it opens, because linking needs a signed-in account. +3. Without `--cloud-project`, the CLI reuses `UNITY_CLOUD_PROJECT`, then the saved default (`defaultCloudProjectId` from `unity cloud project current --format json`), and creates a project only when both are empty. To reuse one, pass `--cloud-project `. If either is set and the user wants a new one, ask first, then clear the saved default with `unity cloud project clear-default` and remove `UNITY_CLOUD_PROJECT` from the link command's own environment in step 6 (for example `env -u UNITY_CLOUD_PROJECT unity projects link cloud ...`), because your shell inherited it and the user unsetting it in theirs doesn't change yours. Recheck both are empty before step 6 creates the project. +4. Check `Packages/manifest.json` for `com.unity.pipeline`: closing gracefully, `--until-ready` and `script eval` need it. If it is missing, add it with `unity pipeline install --project-path ` (Unity 6.0+), say so in the report, and run `unity status --until-ready --project-path ` before closing, because an open Editor loads Pipeline only after it refreshes: on `STATUS_PIPELINE_LOAD_PENDING`, ask the user to focus the Editor and check again. If it can't be added or doesn't load, ask the user to save and close the Editor themselves, and in step 7 check only the asset. +5. `unity close ` exits without saving, so ask the user to save their work first, then run it: an open Editor keeps the old link and can save it back over the new one. +6. Run `unity projects link cloud --format json`, plus `--cloud-project ` when reusing. When it will create a project, first ask whether the game is directed at children under 13 and add `--coppa compliant` if so: the default is `not_compliant`. Never pass `--coppa` with `--cloud-project` (error `COPPA_ARGS_CONFLICT`); change an existing project's COPPA setting in the Unity Cloud dashboard. +7. Verify: if `data.editor.restartRequired` is `true`, an Editor still had the project open: close it, then check the asset still holds the new ID, and if not rerun with `--cloud-project `. Reopen with `unity open --until-ready --format json` (a plain `unity open` returns before the Editor can answer commands) and check `cloudProjectId` in the asset and `CloudProjectSettings.projectId` (via `unity command script eval --project-path `) equal `data.cloudProject`'s ID. Without Pipeline, `--until-ready` times out, so reopen with plain `unity open `, check only the asset's ID, and report that the Editor-side check was not run. On failure, stop and report the error code. +8. Never hand-edit the asset or write an Editor-side linker: a manual edit can mismatch project and organization IDs. diff --git a/skills/build-multiplayer-game/references/multiplayer-play-mode.md b/skills/build-multiplayer-game/references/multiplayer-play-mode.md new file mode 100644 index 0000000..00e438e --- /dev/null +++ b/skills/build-multiplayer-game/references/multiplayer-play-mode.md @@ -0,0 +1,245 @@ +# Multiplayer Play Mode (MPPM) testing + +Links in this file resolve to the skill directory's `references/` folder, the folder this file is in. Project and package paths in code spans are relative to the user's project or the package root. + +## Contents + +- [Overview](#overview) +- [Availability — probe first](#availability--probe-first) +- [Commands](#commands) +- [Clones: drive the game, never the project](#clones-drive-the-game-never-the-project) +- [Netcode commands](#netcode-commands) +- [Who hosts, and how clients join](#who-hosts-and-how-clients-join) +- [Dedicated server: Multiplayer Roles](#dedicated-server-multiplayer-roles) +- [Running a host + client test](#running-a-host--client-test) +- [Network conditions in clones](#network-conditions-in-clones) +- [Final testing with built players](#final-testing-with-built-players) +- [Notes](#notes) + +## Overview + +Verifying netcode needs two or more player processes in the same project. **Multiplayer Play Mode (MPPM)** runs them as *virtual players* — clone Editors of the main project that enter Play mode together and run the **same build**, so it is the closest local stand-in for separate machines (host + client). + +A **Play Mode Scenario** is a project asset (default `Assets/Settings/PlayMode/.asset`) that declares the roster: the Main Editor plus any `clone` (virtual-player Editor) or `local` (built player) players. You author a scenario, make it active, then start it — which enters Play mode and launches every declared player. + +The `com.unity.pipeline` package exposes all of this as `editor.playmode` CLI commands, invoked as `unity command editor.playmode `, so the roster, the run, and each instance's state can be driven and read without a human clicking. Running these commands — installing the package, keeping the Editor ticking (`editor set_auto_tick --enabled true`), auth — is the **unity-cli** skill's job; this page covers only the multiplayer-specific commands and flow. + +## Availability — probe first + +A scenario runs inside the live Editor, so first confirm one is connected, then probe for the scenario commands. They exist only when the project has **`com.unity.multiplayer.playmode`** installed; otherwise they are compiled out. Command names have changed between releases, so list them first: + +```bash +unity status --format json # a connected Editor reports state: ready; if none, open the project first +unity command editor.playmode # lists the group's commands +``` + +If `start_scenario` and the other `*_scenario` commands are absent, MPPM is unavailable — verify with standalone host and client players launched by hand, as in the main workflow, and record a gap in the report's Verification line only if that is also not possible. `list_instances` works without MPPM; the scenario and player commands need it. The command surface is the same for MPPM 2.x and 3.x; read the installed `com.unity.multiplayer.playmode` version from `packages-lock.json` when an API differs. + +A missing command fails as "unknown command". When a name fails, re-list the group before debugging the name. + +To see why, or to confirm which netcode package and version the project uses, read the installed packages rather than relying on the command listing alone: + +```bash +unity command package list # is com.unity.multiplayer.playmode present? which netcode package and version? +``` + +## Commands + +All are `unity command editor.playmode `. They split into authoring the roster, running it, and discovering the live instances. + +| Command | Does | +|---|---| +| `list_scenarios` | List the Play Mode Scenario assets in the project. | +| `create_scenario --name [--path ]` | Create a scenario (auto-adds the Main Editor player). Path defaults under `Assets/Settings/PlayMode/`. It is **not active**: run `set_active_scenario` next, because `add_player` and `start_scenario` act on the active scenario. | +| `list_players [--path ]` | The players a scenario declares, with the ids `remove_player` takes. Defaults to the active scenario. Use `list_instances` to find running clones. | +| `add_player --type clone\|local [--name ] [--path ]` | Add a player to the active scenario (or `--path`) — **state must be Idle**, so add players before `start_scenario`. `clone` = a virtual-player Editor (at most 3); `local` = a built player. MPPM renames clones to `Player 2`, `Player 3`, … when it reloads the scenario, so don't rely on `--name`. It can't set a player's tags or role. | +| `remove_player --id --confirm true [--dry-run true] [--path ]` | Remove a player (destructive; `confirm` required, `--dry-run` previews). | +| `set_active_scenario --path ` | Make a scenario active — **Idle only**. | +| `start_scenario` | Enter Play mode and launch the active scenario's players; with none set it runs the default scenario, the main Editor alone. Returns immediately; players boot **asynchronously**. | +| `get_scenario_status` | Live scenario state plus one entry per declared player: `state`, `reachable`, and once up, `port`, `vpId`, `projectPath`. | +| `stop_scenario` | Exit Play mode and stop the players; state settles asynchronously. | +| `list_instances` | Every Editor reachable over the pipeline — the main Editor plus each live clone — with the `projectPath` and `port` to target it directly. | +| `set_run_in_background --enabled true` | Keep an unfocused Editor's Play mode updating at full rate. This Editor's session only: clones and builds use the project's own value. For a scenario, set that instead — see [Notes](#notes). | + +Other pipeline commands the flow uses. **Where** each may run matters — see [Clones: drive the game, never the project](#clones-drive-the-game-never-the-project): + +| Command | Runs on | Use in an MPPM test | +|---|---|---| +| `script recompile`, `script recompile_status` | Main Editor only | Compile before starting the scenario, so compile errors surface before players launch. | +| `test run --mode playmode` | Main Editor only, scenario stopped | Run netcode Play mode tests. It enters and exits Play mode itself, which MPPM owns on a clone. | +| `editor status` | Any instance | A clone is ready when its own status reports `playMode: playing`. | +| `console get [--level error]` | Any instance | Read an instance's console (errors and the packages' connect messages). Bare `console` is only the group name. | +| `script eval --code ""` | Any instance | Read live state the [netcode commands](#netcode-commands) don't show, or call a test hook. | +| `job wait --condition '' --tolerate-missing true` | Any instance | Wait until a condition holds (client connected, ghost spawned) instead of polling with `script eval`. Add `--async true` (then `job wait_status`) when the condition depends on a command you still need to send: a sync wait holds that instance's command queue. | + +## Clones: drive the game, never the project + +A clone runs out of `/Library/VP/`, a mirror of the main project with a **read-only asset database**. Its running game — loaded scene, live objects, memory — is its own; its project is not. + +| On a clone | | +|---|---| +| **Runtime state** — reading live objects, console, screenshots, input, calling methods on the running game | Fine. This is what a virtual player is for. | +| **Project state** — creating, editing, importing or saving assets and scenes, settings, packages, recompiles | Never. Do it on the main Editor. | +| **Entering or exiting Play mode** | Never. MPPM drives each clone's Play mode from the scenario; use `start_scenario` / `stop_scenario` on the main Editor. | + +Nothing enforces this: a project write sent to a clone is accepted, then fails or lands on the mirror and surfaces later as a desync rather than an error. When a fix needs a project change, stop the scenario, make the change on the main Editor, and start the scenario again. + +## Netcode commands + +Both netcode packages add their own `unity command` groups. Use them instead of `script eval` wherever they cover what you need, because they read the running worlds without adding code to the project and name the fields to compare. List a group before using it (`unity command netcode`, `unity command netcode.gameobjects`), because groups and commands differ between package versions; when a group or command is missing, fall back to `script eval`. Each command's description comes with the listing; NGO's are also on the NGO `unity-cli-commands` page. + +| Need | Unity Netcode | NGO | +|---|---|---| +| Setup problems, before Play mode | `netcode audit` | `netcode.gameobjects audit` | +| Start a role without a session | No command: turn the automatic bootstrap off (`netcode.config set --field enable_client_server_bootstrap --value DisableAutomaticBootstrap`), then `script eval` `Netcode.StartAsHost` on the main Editor and `Netcode.Connect` on each clone. Play Mode Type (`netcode.playmode get_settings`) is shared by the main Editor and its clones, so it can't give them different roles | `netcode.gameobjects.session start --mode Host` (main Editor) or `--mode Client` (clone) | +| Wait until clients are connected | `netcode.session wait_ready --min_clients ` | `netcode.gameobjects.session wait_ready` | +| Connection state and RTT | `netcode get_connection_state` | `netcode.gameobjects status`, `list_clients` | +| Replicated state on this instance | `netcode.ghost list`, then `netcode.ghost get --ghost_id ` (shows `GhostField` values) | `netcode.gameobjects list_objects`, then `get_object` (ownership and behaviours only; read `NetworkVariable` values with `script eval`) | +| Disconnect and rejoin | `netcode.session disconnect`, `reconnect`, `kick` | `netcode.gameobjects.session kick`, `reconnect` | +| Prediction cost and mispredictions | `netcode.profiler get_rollback_metrics` on a client | Not applicable (no prediction) | +| Connect and driver log lines | `netcode.debug set_log_level` to Debug, then `console get` | `netcode.gameobjects.config set --field log_level` | +| Network conditions | `netcode.simulator` | `netcode.gameobjects.simulator` | + +`netcode.ghost diff` and `netcode.tracing` compare client and server worlds inside one process, so they don't work across MPPM instances: run `netcode.ghost get` on the host and on each clone and compare the fields instead. + +## Who hosts, and how clients join + +Starting a scenario only launches the processes. Every instance runs the same code, so nothing decides on its own which one hosts and which ones join — decide it explicitly. + +Drive the roles from outside, through the pipeline: the main Editor hosts, each clone joins. + +- **Netcode only (no session):** for NGO, start the roles with the [netcode commands](#netcode-commands). For Unity Netcode, start them with `script eval` calls to the `Netcode` facade, as that table says, because no command starts a role. +- **Through session connectors** (the game's create and join run on `SessionConnectorBehaviour`s): no hook class, because the game already has the entry points. Once every instance reports `playMode: playing`, run `unity command services.multiplayer run_session_connector --game-object ""` on the main Editor (a GameObject name, or its `Parent/Child` path when the name repeats) and read the join code from the session it returns, then run it on each clone with `--instance --game-object "" --join-code `. If the group has no `run_session_connector`, call what the buttons call with `script eval` instead: the host behaviour's `Execute()` on the main Editor, `list_sessions` for the code, then `SessionConnector.WithJoinByCode` and the join behaviour's `Execute()` on each clone. Pass when `list_sessions` on every instance shows the same session `Id`, `IsHost` true only on the main Editor, and `PlayerCount` equal to the number of instances. +- **Through session code** (create, then join by code, written against the Session API): the netcode commands can't create or join a Multiplayer Services session, so add a small test-only hook class to the project (on the main Editor, before starting the scenario), and remove it when verification is done, because verification code must not stay in the user's project. It exposes, for example: + +- `StartHost()` — creates the session and stores its join code in a static `JoinCode`, +- `Join(string code)` — joins that session, +- static `HasJoinCode` for `job wait`. + +Then, once every instance reports `playMode: playing`, start the host on the main Editor, read `JoinCode` back, and pass it to each clone (step 6 below). + +MPPM player tags (`CurrentPlayer.Tags`, or `CurrentPlayer.ReadOnlyTags()` on MPPM 2.x; always empty outside the Editor) are the in-project alternative, but `add_player` can't set tags, so a scenario built from the CLI has none. + +Two consequences of clones being separate processes: + +- **Each clone signs in as its own anonymous player**, because it has its own data path. Host and clients get distinct player ids without any extra setup. +- **Services only progress in Play mode.** Sign-in, session and Cloud Code calls advance only while the scenario is playing, so issue them after the instances are ready. + +## Dedicated server: Multiplayer Roles + +When step 3 chose a dedicated server, run the main Editor as the server and the clones as clients, so each process strips what its build would. Multiplayer Roles decide this: each GameObject or component is kept for some roles and stripped from the others, and each Editor plays as one role. Use the `multiplayer.role` and `settings.multiplayer_roles` commands, not `script eval` over the roles API. The group needs Unity 6000.6+, so run `unity command multiplayer.role` first and check that it is listed. + +Before you set roles, and again if a step below fails, read the version-matched pages, because what a role strips and where a scenario sets it can change between releases. Read them the way the skill's Documentation section describes for packages: the installed package's `Documentation~` first, otherwise `https://docs.unity3d.com/Packages/@/manual/.html`. + +- Dedicated Server (`com.unity.dedicated-server`): `multiplayer-roles`, `content-selection` +- Multiplayer Play Mode (`com.unity.multiplayer.playmode`): `play-mode-scenario/play-mode-scenario-configurations`, `mppm-reference/play-mode-scenario-window-reference` + +First check that `Packages/manifest.json` lists the Dedicated Server package, `com.unity.dedicated-server`. The Editor turns on its Multiplayer Roles features, including content selection and the role field, only while that package is installed, so without it the steps below strip nothing. If it is missing, ask the user, then add it through the **unity-package-management** skill. + +1. Turn roles on, because nothing is stripped and no scenario applies a role until they are: + + ```bash + unity command settings.multiplayer_roles get + unity command settings.multiplayer_roles set --settings '{"enabled":true}' --confirm true + ``` + +2. Mark what each role keeps. `role` is `client`, `server` or `client_and_server`: + + ```bash + unity command multiplayer.role set_game_object --target --role server # the GameObject + unity command multiplayer.role set_component --target --type AudioSource --role client # one of its components + ``` + + Don't run `multiplayer.role set_build` for a Play Mode test. It changes the role the active build profile builds for and nothing restores it, so the next client build would strip its client-only objects. Use it only when the user asks for a server build. That build also needs the target platform's dedicated server module; see [Final testing with built players](#final-testing-with-built-players). + +3. Give each scenario player its role. In a Play Mode Scenario every player's role comes from the scenario, the main Editor included, and every player defaults to `client`. The scenario applies those roles when it starts and restores the main Editor's own role when it stops, so `multiplayer.role set_active` does not change a scenario run. Clones are therefore clients already; make the main Editor the server by writing its role into the scenario asset while the scenario is Idle: + + ```bash + unity command editor.playmode list_players --path # rows are in stored order: row N (from 0) is item N; find the row whose type is main + unity command component set_field --target --field "m_Settings.m_InstanceItems.Array.data[].m_Settings.RoleMask" --value Server + unity command editor save_project # set_field changes the asset in memory; this writes it to disk + ``` + + The value is a bare enum name, `Client`, `Server` or `ClientAndServer`; a quoted `'"Server"'` is refused. `component get_fields` can't show this field, so check the result with step 5. The field path is the scenario's internal layout, so if `set_field` reports it not found, ask the user to set **Multiplayer Role** to **Server** for the Main Editor in the Play Mode Scenario window instead, and say that the main Editor would otherwise run as a client. If `editor save_project` isn't listed, ask the user to save the project. Then tell the user the scenario asset now runs the main Editor as the server, and ask whether to keep that or set it back to `Client` after the test, because the change is in a project file their next commit will pick up. + + `list_players` leaves out a broken player entry, such as one left by a removed package, so its rows no longer match the stored items. If the role check in step 5 reads `client` on the main Editor after the write, use the Play Mode Scenario window. `editor save_project` also writes every other unsaved asset and setting in the project. If the user has unsaved changes of their own, ask before running it. +4. Without a scenario, plain Play mode runs the main Editor alone, as the role `unity command multiplayer.role set_active --role server` sets. Run `set_active` in Edit Mode, because it refuses while playing. +5. After `start_scenario`, check each instance before driving it, because a wrong role fails later as a missing object rather than an error: `unity command multiplayer.role get_active` on the main Editor reads `server`, and `unity command --instance multiplayer.role get_active` reads `client`. + +Then start a server, not a host, on the main Editor in step 6 of the run below, and join from each clone as before. + +## Running a host + client test + +Drive these through the **unity-cli** skill. + +Before the run, check how to address a clone, because the flag depends on the installed CLI. Run `unity command --help`: if it lists `--instance`, address a clone with `--instance `, the name or `vpId` that `list_instances` reports for it once the scenario runs, because MPPM can rename clones when it reloads the scenario, so the name you gave `add_player` may no longer match. If it doesn't, the CLI predates the flag: replace every `--instance ` below with `--project-path `, taking the path from `list_instances`. + +A minimal host-plus-one-client run: + +```bash +unity status --format json # 0. a connected Editor reports state: ready +unity command --help | grep -- --instance # no match: use --project-path wherever --instance appears below +unity command editor.playmode # 1. probe; use standalone host/client players if the *_scenario commands are missing +unity command editor.playmode list_scenarios # 2. reuse an existing scenario if one fits +unity command editor.playmode create_scenario --name NetTest # else make one (Main Editor player is added for you) +unity command editor.playmode set_active_scenario --path Assets/Settings/PlayMode/NetTest.asset # create_scenario does not make it active +unity command editor.playmode add_player --type clone --name Client1 # add a client to the active scenario — must be Idle +unity command editor.playmode get_scenario_status # confirm active is NetTest and isDefaultScenario:false (the default runs the main Editor alone) +unity command script recompile # 3. add the host/join hooks if the test goes through session code (not connectors), compile on the main Editor, confirm no errors +unity command script recompile_status +unity command netcode audit # or netcode.gameobjects audit: fix what it reports before starting +unity command settings.player get # run-in-background must be true: every instance needs it, and clones read only the project's value +unity command settings.player set --settings '{"run-in-background":true}' --confirm true # if it is false; see Notes +unity command editor.playmode start_scenario # 4. started:true means accepted, not ready; a clone's first launch can take a minute or more +unity command editor.playmode list_instances # 5. poll until each clone is listed; note its name or vpId as +unity command --instance editor status # then until that clone reports playMode: playing and runInBackground: true (no clone after ~2 min: see Notes) +# 6. assign roles, then drive each instance's running game by its own instance name: +unity command script eval --code "MyGame.NetTestHooks.StartHost(); return true;" # main Editor hosts (dedicated server: a StartServer() hook instead, see Dedicated server: Multiplayer Roles) +unity command job wait --condition '{"member":"MyGame.NetTestHooks.HasJoinCode","op":"equals","value":true}' --timeout 60 +unity command script eval --code "return MyGame.NetTestHooks.JoinCode;" # read the join code +unity command --instance script eval --code "MyGame.NetTestHooks.Join(\"\"); return true;" # clone joins +unity command netcode.session wait_ready --min_clients 1 # host waits for the client (NGO: netcode.gameobjects.session wait_ready) +unity command --instance netcode get_connection_state # the clone's connection, endpoints and RTT (NGO: netcode.gameobjects status on the clone, list_clients on the host) +unity command --instance console get # check the client's console for errors +unity command netcode.ghost list # find the ghost id on the host (NGO: netcode.gameobjects list_objects) +unity command netcode.ghost get --ghost_id # the host's replicated fields +unity command --instance netcode.ghost get --ghost_id # the same ghost on the clone; compare +unity command editor.playmode stop_scenario # 7. stop; mutating the roster again needs Idle, so stop first +``` + +Find clones with `list_instances`, because it reports each running clone's name, `projectPath` and `port` directly. Don't gate readiness on a player's `state` either: it can stay at `Launching` for the whole run while the clone is up and playing. + +`NetTestHooks` and its members are placeholders for the hook class described in [Who hosts, and how clients join](#who-hosts-and-how-clients-join). With session connectors, replace the three hook lines with the connector steps there. Without a session, replace the three hook lines with the role commands in [Netcode commands](#netcode-commands). + +**Assert parity (invariant 9):** what worked in one process holds across instances — the host's authoritative values and the clients' replicated ghosts agree, and late-join and disconnect behave. Read the same ghost or object on the host instance and a client instance with the [netcode commands](#netcode-commands) and compare the fields, using `script eval` only for values they don't show, because reading live state needs no logging code that would have to be removed afterwards. + +## Network conditions in clones + +Test latency, jitter and packet loss in the clones throughout development, not in a late pass, because both netcode stacks' emulators run in the Editor and so in every clone. Read the stack's page before configuring it: + +- Unity Netcode: the PlayMode Tool network emulator, opened in each clone (*Use the Playmode Tool window with Multiplayer Play Mode* on the Netcode `testing/playmode-tool` page). From the CLI, the `netcode.simulator` group (`list_presets`, `set`, `get`, `lag_spike`, `timeout`) sets it per instance through `--instance` (or `--project-path`); it applies live to client worlds in Play mode. +- NGO: the Multiplayer Tools Network Simulator (NGO `tutorials/testing/testing_with_artificial_conditions` page), or the `netcode.gameobjects.simulator` group with the same commands (its `list_presets` needs Multiplayer Tools installed; `set` with explicit values works without it). A hybrid session's GhostObject traffic needs `netcode.simulator` instead. + +List the group first (`unity command netcode.simulator`), because command names change between releases. Set conditions on the clients, then confirm the measured RTT rose before trusting the run. + +## Final testing with built players + +Once the work passes in the clones, add built players to the same scenario as local instances (`add_player --type local`) for what clones cannot show: build-only code and stripping, target platforms and devices (MPPM local instances include Android devices), release-build network conditions, a run over the real transport or Relay path, and anything the user needs as a shippable build. The scope and order are in the verification gate's *Final testing* section; the MPPM docs describe local instances as the step closer to the final build (`instance-types/local-instance` in `https://docs.unity3d.com/Packages/com.unity.multiplayer.playmode@/manual/`, with `` the installed `com.unity.multiplayer.playmode` major.minor, or the package's `Documentation~`). + +A dedicated-server local instance, or any server build, needs the dedicated server module for its platform, because the scenario rejects a build profile whose module isn't installed. The main Editor and clones need no module to play the server role. Check with `unity modules ` for `linux-server`, `windows-server` or `mac-server`. If the one you need is missing, ask the user before installing it, because it is a download of 0.5–2 GB, then run `unity install-modules --editor-version --module `. + +## Notes + +- Each clone is a separate Editor with **its own pipeline server** (own `port`, project under `Library/VP/`), so you address it by `--instance `, or by `--project-path` on a CLI without `--instance` (see [Running a host + client test](#running-a-host--client-test)). Never pass a name to `--project-path`. `list_instances` and the `get_scenario_status` players give the name, path and port. +- **Every instance needs Run in Background, and clones read only the project's value.** An unfocused instance without it stops its player loop, which looks like a netcode timeout, and a clone is almost always unfocused. `set_run_in_background` changes only the Editor it runs in, so turn the project's value on from the main Editor with `settings.player set` before `start_scenario`; a clone that is already running may keep the old value until it restarts. If `start_scenario` returns a `note` about Run in Background, act on it. If `settings.player get` has no `run-in-background` field, the installed pipeline cannot set it: turn it on in the main Editor with `unity command script eval --code "UnityEditor.PlayerSettings.runInBackground = true; UnityEditor.AssetDatabase.SaveAssets(); return true;"`. +- **Never cache a port.** Starting a scenario can move the main Editor's pipeline port, and it doesn't move back on stop. Re-read `list_instances` each time. +- `stop_scenario` exits Play mode. With MPPM's **Keep Active** setting on, the clone Editors stay running and reachable, which makes the next start fast. Close them from the Multiplayer Play Mode window to free the machine. +- If no clone appears in `list_instances` within about two minutes of `start_scenario`, stop the scenario and verify with standalone host and client players instead of waiting longer. Record a gap in the report's Verification line only if that is also not possible. +- Judge a clone's readiness by its own `editor status`, not by messages in the main Editor's console. +- The mutating commands (`add_player`, `remove_player`, `set_active_scenario`) are refused unless the scenario state is `Idle`; `stop_scenario` first. +- Before each `start_scenario`, check that `get_scenario_status` shows your scenario as `active`, because a plain `editor.playmode start` can reset it to the default scenario, which runs the main Editor alone. +- Don't hand-edit the scenario `.asset` YAML while the Editor is open. Change the roster through the `editor.playmode` commands so the running Editor stays in sync. +- **At most 3 clones**, so 4 players including the main Editor. For more, add built players with `add_player --type local`. +- MPPM shares the main project's assets and scripts across clones, so it exercises the **same** netcode code the host runs, and with the emulator on it covers behaviour under latency too. A multi-machine run over the real network, a dedicated-server build, and final performance numbers on target hardware belong to final testing, not to everyday verification. +- A clone joining the main Editor satisfies the verification gate's cross-process connect: the IPC driver works only inside one process, so a clone that connects, and has no server world of its own, used the socket driver; its console shows that selection only with the Netcode log level set to Debug. Build a player (`build set_profile`, then `build run`) and add it with `add_player --type local` only for final testing (see [Final testing with built players](#final-testing-with-built-players)). +- `runtime simulate_*` drives a clone's Game view as well as a development Player, but only while that instance's window has focus: an unfocused Editor drops the event and still reports success. Before simulating input on an instance, run `unity command --instance editor focus`, then confirm the effect by reading the game's state, never by the command's result. When two instances need input in the same step, call a test hook through `script eval` instead, because only one window can have focus at a time. `runtime set_time_scale` works only on development Player builds. For network conditions in clones, use the netcode simulator commands in [Network conditions in clones](#network-conditions-in-clones). diff --git a/skills/build-multiplayer-game/references/netcode-for-entities.md b/skills/build-multiplayer-game/references/netcode-for-entities.md new file mode 100644 index 0000000..2159546 --- /dev/null +++ b/skills/build-multiplayer-game/references/netcode-for-entities.md @@ -0,0 +1,22 @@ +# Direct ECS ghosts + +Links in this file resolve to the skill directory's `references/` folder, the folder this file is in. Project and package paths in code spans are relative to the user's project or the package root. + +Use direct ECS authoring when the team is ECS-native, gameplay needs jobs, buffers or fine-grained ghost configuration, scale is high, or GhostObject lacks a required capability (Netcode `ghostobject/ghostobject-use` page). Read the Netcode page for each topic before writing it: + +- Ghost modes, send rates and `[GhostField]`/`[GhostComponent]`: `ghost-snapshots`, `ghostfield-synchronize`, `ghostcomponentattribute`. +- Input and prediction: `command-stream`, `prediction-n4e`, `prediction-details` (partial snapshots, `GhostGroup`). +- Worlds and host modes: `client-server-worlds`, `single-world-host-mode`, `binary-worlds-host-mode`. Host-mode consequences for the game are in [architecture.md](architecture.md). +- Relevance and importance: `optimization/optimize-ghosts`. Relevance is also an information-security boundary, so use it to hide what a client must not know. +- Physics and lag compensation: `physics`, `server-rewind`. +- RPCs and the connection flow: `rpcs`, `network-connection`. +- SubScenes and prespawns: `ghost-spawning`, `prespawned-ghosts`. Don't assume they carry over to GhostObjects. + +Rules the docs don't give, or that models get wrong: + +- **Owned interpolated ghosts still send commands;** predict a ghost only so its owner sees results without a round trip (*Input* in [syncing-gameplay.md](syncing-gameplay.md)). +- **`NetcodeConfig.AutomaticStateReplication` defaults to true,** so Netcode adds `NetworkStreamInGame` on both sides as soon as a connection is up. Don't add it yourself unless you turned that off to gate gameplay on approval or content loading. +- **A single-world host can't hide ghosts from itself with relevancy,** because it keeps the authoritative ghosts; hide distant rendering separately. +- **Joints across simulation worlds don't work.** Interpolated ghosts are kinematic on clients, and bodies in separate physics worlds can't interact, so a predicted ghost jointed to an interpolated or client-only body treats it as an immovable anchor or not at all. Use `CustomPhysicsProxyAuthoring` to mirror a predicted ghost into a client-only world. +- **Spell out the assembly references in your own `.asmdef`,** because a missing one fails as an opaque source-generator error pointing at an unrelated file rather than a missing type (for example `Unity.Entities` without `Unity.Collections`). The set is `Unity.NetCode` (the assembly; the namespace is `Unity.Netcode`), `Unity.Entities`, `Unity.Entities.Hybrid`, `Unity.Transforms`, `Unity.Collections`, `Unity.Mathematics`, `Unity.Burst` and `Unity.Networking.Transport`, on test assemblies too. +- **Test a single-world host from a second process** (a Multiplayer Play Mode clone counts) with latency emulated on the clients, because the host itself never replays and can't emulate lag. diff --git a/skills/build-multiplayer-game/references/netcode-lifecycle.md b/skills/build-multiplayer-game/references/netcode-lifecycle.md new file mode 100644 index 0000000..652af1c --- /dev/null +++ b/skills/build-multiplayer-game/references/netcode-lifecycle.md @@ -0,0 +1,383 @@ +# Game sessions and lifecycle + +## Contents + +- [Start and connect](#start-and-connect) +- [GameObject-layer rules](#gameobject-layer-rules) +- [World creation and transport driver selection](#world-creation-and-transport-driver-selection) +- [Prefabs and spawning](#prefabs-and-spawning) +- [Scene and content state](#scene-and-content-state) +- [Canonical game-session state](#canonical-game-session-state) +- [Join, drop, leave, and rejoin](#join-drop-leave-and-rejoin) +- [Failure triage](#failure-triage) +- [Error strings](#error-strings) +- [Unhappy-path tests](#unhappy-path-tests) +- [Proving a build is current](#proving-a-build-is-current) + +This reference covers the handoff from a connection (a Multiplayer Services session +or a direct connect) to gameplay and the join/drop/rejoin lifecycle. Creating the session, matchmaking, and hosting come +first; the session step of the workflow covers them. + +Identity splits three ways. Account identity (sign-in, authentication) belongs to +`build-live-game`. Session membership and choices made before the game session exists, +carried as session player properties, belong to the session layer. The slot and team inside the +game session, and anything derived from them, belong here. + +Links in this file resolve to the skill directory's `references/` folder, the folder this file is in. Project and package paths in code spans are relative to the user's project or the package root. + +## Start and connect + +For the GameObject ghost layer, the static `Netcode` class starts, inspects and stops +game sessions. Read the Netcode `ghostobject/ghostobject-connections` page for its +connect, listen, host, role, connection-event and shutdown APIs before writing that +code. `Netcode.StartAsHost` also takes an optional host-world-mode argument that the +page does not show; confirm its signature in the installed source before passing it. + +When the session's default network handler (`WithRelayNetwork`/`WithDirectNetwork`) already starts Netcode, the session +creates the worlds and connects: skip the `Netcode` start calls and the automatic +bootstrap's world, which by default already listens (and, in binary worlds, +self-connects) on `ClientServerBootstrap.AutoConnectPort` (7979). Otherwise start +Netcode here. + +Single world is the default host mode for `Netcode.StartAsHost`, and the only one +GhostObjects support (Netcode `ghostobject/ghostobject-connections` page); pass +`NetcodeConfig.HostWorldMode.BinaryWorlds` only for direct ECS ghosts. A host started +by the session's default network handler instead reuses +any bootstrap-created worlds, or creates separate client and server worlds when none +exist. So for GhostObjects, start the host with `Netcode.StartAsHost` and use the +session only for membership and connection details. To host or join a GhostObject game +over Relay, assign a Relay `INetworkStreamDriverConstructor` to +`NetworkStreamReceiveSystem.DriverConstructor` before calling `StartAsHost` or `Connect` +(Netcode `networking-using-relay` page). For direct ECS ghosts, disable the +automatic bootstrap before starting the session and treat that host as binary worlds. + +The connection defaults are tuned for tolerance, not for a join screen: +`MaxConnectAttempts: 60` with `ConnectTimeoutMS: 1000` on the generated +`NetcodeConfig.asset` means a mistyped or dead direct-IP address takes about a +minute to fail. Any game with a manual IP entry field should lower the attempt +count, and should verify the resulting failure time. + +Ghost replication starts on its own: `NetcodeConfig.AutomaticStateReplication` +defaults to true, so Netcode adds `NetworkStreamInGame` on both sides once a +connection is fully connected. Don't add `NetworkStreamInGame` yourself, because +Netcode already adds it. To hold replication back until +a peer is approved or its content is ready, follow *Control ghost replication* on the +Netcode `ghostobject/ghostobject-connections` page, and enable replication from one +place that both the host-local path and the remote path reach, so neither side is +missed. + +For direct ECS ghosts, read the Netcode `client-server-worlds` and +`network-connection` pages for creating worlds and requesting listen or connect +before writing that code. + +Every process in a game session (host, server, or client) must run with +`Application.runInBackground` enabled, or its simulation stalls on focus loss and +peers time out; a stalled host freezes every client. Check it rather than assuming +the template's value. Set it as described in `https://docs.unity3d.com/Packages/com.unity.netcode@/manual/network-connection.html` +(replace `` with the `com.unity.netcode` major.minor from +`Packages/packages-lock.json`, or read the package's `Documentation~/network-connection.md` +when that version is not published) +(`runInBackground: 1` in `ProjectSettings/ProjectSettings.asset` is the project-wide +form). Netcode's `WarnAboutApplicationRunInBackground` system logs an error when it +is disabled; suppress it by setting `SuppressApplicationRunInBackgroundWarning` on each +world's `NetDebug` singleton (an instance property, not a static) only when stalling on focus loss is a deliberate, handled choice (e.g. mobile, where +the OS suspends the app regardless and the reconnect flow must cope anyway). + +Recommended order: + +1. Resolve packages and confirm the APIs you will use in the installed source before writing gameplay. Enable + Run in Background project-wide (or decide and document how focus loss is + handled). +2. Complete the session step first: initialize identity/services, create or join + the session, and acquire connection details. +3. Register ghost prefabs on client and server (order matters only when + `GhostPrefabLoadingTimeout` is 0; see *Prefabs and spawning*). +4. Create the selected client/server/host worlds. +5. Bind the transport, listen/connect, and approve the peer before gameplay spawn + and input (replication itself starts automatically unless + `AutomaticStateReplication` is off). +6. Assign each joining participant's slot and derived identity on the authority + and replicate it. +7. Synchronize scene/content state, then spawn the player and begin simulation. + +## GameObject-layer rules + +- **Bootstrap exclusivity.** Automatic world creation and manual `StartAsHost`/`Connect` are alternatives; combining them makes `IsServer` true before any game session exists. +- **Game session first, ghost state second.** Never access `GhostField.Value` when no game session or Netcode world is running, and write it only where `CanWriteState` is true. (On a client, `Awake` already sees replicated values; on the server it sees prefab values — Netcode `ghostobject/ghostobject-replicate` page.) Gate per-frame simulation on game-session-active and ghost-linked state. +- **Shut down symmetrically.** Call `Netcode.Shutdown()` on leave, host loss and `OnDestroy`. Repeated identical per-frame exceptions mean a loop is not gated on game-session state. + +Writing ghost state through the contract (`PredictionUpdate`, `CanWriteState`, `PredictionGatherInput`) and writing predicted values into restored storage are covered in *GhostObject state*, *Input* and *Prediction and replay* in [syncing-gameplay.md](syncing-gameplay.md). + +## World creation and transport driver selection + +Two defaults interact to break every "join a remote host" flow in a +default-configured build: + +1. The automatic `ClientServerBootstrap` creates a host world (single world, the + default) or a ServerWorld and a ClientWorld (binary worlds) at startup whenever `RequestedPlayType` is `ClientAndServer` — + which is every normal (non-client-only, non-server-only) build, including + instances that will only ever join. Under single world, a connect attempt from + that host world throws `You cannot call Connect on a NetworkStreamDriver in a + server or host world.` +2. Under binary worlds, the default `IPCAndSocketDriverConstructor` selects the client driver when + the client world is created and again on each `Connect`: if `RequestedPlayType` is + not Client, the network simulator is off, and a non-host ServerWorld exists in the + same process, it registers the **IPC** driver (in-process, loopback-only) instead + of UDP. A remote address passed to `Netcode.Connect` is then silently rewritten to + loopback. This surfaces only as a warning in Player.log — never as an error or a + failed return value — so the client appears to connect (or times out) identically + for every address typed in. + +Rule: **a join-only client must have no server or host world in its process when it +connects.** The auto-created server or host world serves no purpose for it, and by +default it listens on `AutoConnectPort` (7979): `Netcode.Connect` +and `Netcode.StartAsHost` both lazily create the worlds they need +(`Runtime/GameObjectLayer/Netcode.cs`), so hosting still works without it. + +Mitigations, in preference order. Read the named page before applying one, and again +if it fails: + +1. A custom `ClientServerBootstrap` that creates only the local world and sets + `AutoConnectPort` to 0, so nothing connects before the player picks a role + (*Customize the bootstrapping flow* on the Netcode `client-server-worlds` page, and + the Netcode `network-connection` page). The `Netcode` facade then creates + client/server worlds on demand for host and join. Wrong variant: returning true + from `Initialize` without creating any world fails an Entities assertion + (`World.DefaultGameObjectInjectionWorld` must be set). +2. Disable the automatic bootstrap on the `NetcodeConfig`, or for one scene with + `OverrideAutomaticNetcodeBootstrap` (*Override bootstrapping for a single scene* on + the Netcode `client-server-worlds` page), then create worlds explicitly. +3. Build join-only clients with the client-only Netcode Client Target (Netcode + `project-settings` page), which creates only a ClientWorld. +4. Dispose the unused auto-created server or host world before the first client connect. + +Verify the selected transport from the client's log after connecting (Player.log, +or a virtual player's console). The driver-registration lines +(`[DefaultDriverConstructor.RegisterClientUdpDriver]` versus `RegisterClientIpcDriver`) +are Debug-level, below Netcode's default log level, so set the log level to Debug +first (read the Netcode `testing/logging` page for how); otherwise their absence proves nothing. The warning `IPC +interfaces only support loopback address` appears at the default level and is the +smoking gun that the remote address was discarded. + +## Prefabs and spawning + +`GhostObject` prefabs register automatically when their asset loads. For addressable +or dynamically loaded content, or to change GhostObject settings from code first, +follow *Register a prefab yourself* on the Netcode `ghostobject/ghostobject-replicate` +page. Enable **Skip Automatic Prefab Registration** on the prefab asset in the +Inspector, because the value is copied at import and setting it at runtime does +nothing. + +Prefab order between client and server matters only when +`NetcodeConfig.GhostPrefabLoadingTimeout` is 0; at the default (-1) or a positive +value, clients load prefabs in any order. The options are under *Control ghost +replication* on the Netcode `ghostobject/ghostobject-connections` page. + +Spawn authoritatively with ordinary `Object.Instantiate(registeredPrefab)`; remote +replicas come from snapshots. For a client predicted spawn, follow *Spawn an object +from prediction* on the Netcode `ghostobject/ghostobject-replicate` page, and also +check the connection is in game and the ghost collection is initialized, because +rollback otherwise creates duplicates. Destroy the GameObject, not its linked entity. + +High-churn gameplay should be designed carefully: a deterministic projectile is +often a spawn event plus local flight and an authoritative hit, rather than a +networked object for every frame of travel. On a single-world host that pattern +needs one extra guard — the host receives its own spawn event for an object it +already owns authoritatively, so gate the local derivation on `IsServer`. See the +note under *Common object plan* in [syncing-gameplay.md](syncing-gameplay.md). + +## Scene and content state + +Every peer must load compatible content before simulation. A mismatched ghost +registry, prefab layout, or build version can reject a connection or desynchronize +serialization. + +Direct ECS ghosts have established SubScene, scene-section, and prespawn flows. +The GameObject layer has no scene-management API equivalent to NGO's +`NetworkSceneManager` (no `Netcode.SceneManager`), and a `GhostObject` authored +straight into a scene without a prefab is rejected. Read the installed package's +`Documentation~/ghostobject/` pages before using any scene flow. + +For a GhostObject project: + +- prefer a persistent bootstrap scene and dynamically registered/spawned gameplay + prefabs; +- coordinate scene transitions through explicit authoritative state plus a + tested local loading flow; +- gate simulation until every required peer reports compatible content and ready + state; +- use direct ECS SubScenes for network scene content when that workflow fits; +- do not claim late-join scene correctness until it has been tested in builds. + +## Canonical game-session state + +Model match flow as compact replicated state: phase enum, authoritative end tick, +participants (each with its authority-assigned slot, team, and whatever identity the +game derives from the slot), score, and ownership. Late joiners receive current state +rather than replaying old events. Keep collections bounded and transfer data that +outlives a game session to a backend. Lifecycle transitions that lock or unlock +participant control (countdown end, match end, respawn) are part of that state and are applied on every +client from the replicated value, never from a local timer or a host-only callback. + +Maintain one writer for each state value. On a single-world host both role checks +are true, with the consequences listed under *Single-world details* in +[architecture.md](architecture.md). + +- `IsClient` does not imply non-authoritative execution on a single-world host. + +## Join, drop, leave, and rejoin + +**Join** + +- Validate build/content version, capacity, ticket, and rules before the joiner's + gameplay spawn and input (and before enabling ghost replication, if + `AutomaticStateReplication` is off). +- Assign each participant's slot and derived identity on the authority as part + of approval, and replicate it before enabling input. One connection may carry + several participants (a shared-screen lobby joining a remote host), so the + join request carries the participant count and each participant's local + choices (character, vehicle, name; one session player may carry several + participants' choices); the authority allocates one slot per participant, + confirms or substitutes each choice, renumbers any locally numbered + participants, re-derives what depends on the slot (color, spawn, HUD + position), and clients render what was replicated. +- Load compatible content, synchronize state, spawn the player, then enable input. +- Make initialization idempotent; repeated connection notifications must not grant + duplicate avatars or inventory. + +**Leave versus drop** + +- A deliberate leave releases the slot immediately. +- A timeout usually preserves player state for a bounded grace period. +- Record enough identity outside the transient connection entity to match a + reconnecting player to held state. + +**Owned objects** + +For every category choose transfer, despawn, or freeze for the grace period. Never +leave ownership behavior implicit. A player avatar usually despawns or freezes; +shared vehicles/structures usually transfer to authority. + +**Rejoin** + +- Restore state rather than granting new state. +- Make repeated reconnect attempts idempotent. +- Expire held state and slots predictably after the grace period. + +**Host loss** + +- A listen server ends when its host leaves unless host migration is designed. +- Host migration is experimental. If a page asks for a scripting define, add it only + if the installed source checks that define, because a define nothing checks changes + nothing. It requires + service-side host election/state storage plus a new Relay allocation and client + reconnection, with auto connect disabled. Read the Netcode + `host-migration/host-migration` page and its subpages first, and confirm in the + installed source that it works with your host mode before promising it to a + GhostObject (single-world) project. Verify the installed package's data-size/region/platform limits, + child-ghost and prespawn behavior, detection time, allocation failure, and known + migration defects before promising continuity. +- Single-world host is not automatically equivalent to binary-world migration. +- Dedicated authority avoids player-host migration. + +## Failure triage + +Check in this order: + +1. Editor and resolved package version; the GhostObject-layer APIs confirmed in its source. +2. Compile errors from bridge source generation. +3. Client/server build and ghost registration mismatch. +4. Transport bound before connect/listen and service credentials still valid. +5. Client "connects" to itself, or the connect behaves identically for every + address: check the client's log for `IPC interfaces only support loopback` — an + in-process ServerWorld (usually the auto-created bootstrap world) forced the + IPC driver and the remote address was never dialed. See + [World creation and transport driver selection](#world-creation-and-transport-driver-selection). +6. Host shows doubled ghosts or a trailing duplicate while clients look correct. + Two causes, one per host mode: in **binary worlds** the authoritative instance + and its client-world replica coexist and presentation isn't gated to `IsClient` + instances; in **single world** there is no replica, so the duplicate is + application-created by a handler that runs because both roles are true. Causes, + fixes, and the `IsServer` rule: [architecture.md](architecture.md). + Check every `[RPC(SendDirection.ServerToClient)]` handler, `Netcode.RPC.Query` + consumer and event callback for an unguarded local spawn or state change. +7. With `NetcodeConfig.AutomaticStateReplication` off: connection approved but + `EnableGhostReplication(true)` never called on one side (the client's or the + server's connection). +8. World/host mode differs from the assumed architecture. +9. Content not ready before player spawn. +10. Timeout/drop interpreted as a deliberate leave. +11. NGO project with Unity Netcode's automatic bootstrap still on. NGO 3.x + installs `com.unity.netcode`, whose bootstrap can open port 7979 in every + process and break an NGO join. `netcode list_worlds` returning worlds in an + NGO-only project means it is running; turn it off with `netcode.config set`. +12. Static state left from an earlier Play session. With domain reload disabled + (Enter Play Mode Options), `NetworkStreamReceiveSystem.DriverConstructor` and + `ClientServerBootstrap.AutoConnectPort` keep values set in a previous session: a + Multiplayer Services session leaves its Relay driver constructor behind, so a + later direct host accepts no connections and reports nothing. Set + `DriverConstructor` to `null` (the default) and restore `AutoConnectPort`, or + restart the Editor. + +## Error strings + +| Exact string | Root cause | Resolution | +|---|---|---| +| `You cannot call Connect on a NetworkStreamDriver in a server or host world.` | A join-only client's automatic bootstrap created a server or host world | Turn the automatic bootstrap off, or use a client-only bootstrap or build target ([World creation and transport driver selection](#world-creation-and-transport-driver-selection)) | +| `IPC interfaces only support loopback address` (warning) | An in-process server world forced the IPC driver, so the remote address was rewritten to loopback | As above; confirm the socket driver at Debug log level | +| `Failed to bind UDP socket because the address is already in use` | Another process already listens on the port (7979): two `ClientAndServer` instances, or Unity Netcode's bootstrap in an NGO project | Turn that bootstrap off in NGO projects; start Unity Netcode roles explicitly with `Netcode.StartAsHost` and `Netcode.Connect` | +| `Listen is not allowed if playmode is set to Client` | Play Mode Type is `Client`; the main Editor and its clones share it | `netcode.playmode set --type ClientAndServer`, then start the roles explicitly | +| `'' has a GhostObject but was authored directly into a scene. Ghosts must be prefabs.` | A GhostObject placed in a scene, not as a prefab instance | Make it a prefab and instantiate it at runtime | +| `SessionException: Starting network failed` with `AssertionException: Should only be called from standalone clients` | The default network handler ran on a single-world host world | GhostObject: start the host with `Netcode.StartAsHost`. Direct ECS: turn the automatic bootstrap off and set `AutoConnectPort` to 0 | +| `There are still connections present` … `Cannot assign the NetworkDriverStore` | The handler reused a client world that had already auto-connected | Set `ClientServerBootstrap.AutoConnectPort` to 0 before the session starts | +| `error CS0103: The name '' does not exist in the current context` (from `script eval`) | An unqualified type outside `UnityEngine` | Fully qualify the type, or add a `using` line | +| `error CS0234: The type or namespace name '' does not exist in the namespace '.Netcode'` | A namespace segment named `Netcode` hides the `Netcode` facade | Rename that namespace segment | + +## Unhappy-path tests + +Run these in Multiplayer Play Mode, with the main Editor and its clones as the +processes, unless a test says final testing (see the verification +gate's *Final testing* section). Use standalone players only when MPPM +is unavailable. + +1. Kill a client process and reconnect during and after the grace period. +2. Kill the host and verify the promised end/migration behavior. +3. Join during active gameplay and verify complete world state. +4. Rejoin twice and confirm one avatar/state grant. +5. Final testing: connect a deliberately mismatched build and show a clear rejection. +6. Load/transition content with a slow client. +7. Join from a second process on a **non-loopback** address and confirm from both + processes' logs that the socket driver was selected. In-process host+client + rides the IPC path and proves nothing about real network connectivity. A + Multiplayer Play Mode virtual player is a separate process, so a join from it + to the main Editor over relay or the machine's own LAN address takes the + socket driver and meets this bar with no extra hardware, scriptably. A join + from a second machine belongs to final testing. +8. Compare the host's rendered view against a client's during active play. + Doubled geometry, a trailing second avatar/ball, or duplicated GUI on the + host means presentation isn't gated to client instances. A regression test + for a bug found here counts only once it has been observed to fail with the + fix removed **and a peer connected** — a solo in-process test takes only + the authority path and can pass in both directions. +9. Repeat under latency, jitter, and loss with the in-Editor emulator in the + clones; repeat over the real Relay/transport path in final testing. +10. Join from two processes that each made a local choice before connecting. + Confirm the authority's assignment wins: no two participants share a slot + or anything the game derives from one, and each client shows the + replicated identity, not the one it chose before the game session. +11. Run a complete game session across two processes and compare it feature by + feature with a single-process game session: anything missing on a client is + either replicated or recorded as a deferral with its reason. + +The measurement loop is in the performance reference. + +## Proving a build is current + +Player-build verification must be checkable, not asserted. Unity does not +rewrite the `.exe` when only managed assemblies change, and a directory's +timestamp does not move when files inside it change, so both things a reviewer +inspects stay frozen at the first build. Compare the last-modified time of the +built game code itself (`_Data/Managed/Assembly-CSharp.dll` under Mono, +`GameAssembly` under IL2CPP) against the newest source change, and confirm the +EditorBuildSettings scene list is non-empty before building. Don't change player +settings or add startup logging to prove it, because those ship with the game. diff --git a/skills/build-multiplayer-game/references/performance-and-scale.md b/skills/build-multiplayer-game/references/performance-and-scale.md new file mode 100644 index 0000000..c30188a --- /dev/null +++ b/skills/build-multiplayer-game/references/performance-and-scale.md @@ -0,0 +1,215 @@ +# Performance and scale + +## Contents + +- [Set budgets before writing netcode](#set-budgets-before-writing-netcode) +- [Starting bands to reason against](#starting-bands-to-reason-against) +- [The levers, in order of impact](#the-levers-in-order-of-impact) +- [Prediction cost](#prediction-cost) +- [How to test — the measurement loop](#how-to-test--the-measurement-loop) +- [Verifying prediction](#verifying-prediction) +- [Common causes of slow multiplayer](#common-causes-of-slow-multiplayer) + +Choosing the right authoring path buys **headroom**; replication design decides whether +the game actually spends it well. A project on the fastest path still ships a laggy +game if it replicates everything, every tick, to everyone. + +Use this file when the game has a scale/performance requirement, when the developer +reports lag, jitter, rubber-banding, or bandwidth problems, or before signing off on an +architecture. **This file also owns how to test** — every other file defers here for +that. + +Links in this file resolve to the skill directory's `references/` folder, the folder this file is in. Project and package paths in code spans are relative to the user's project or the package root. + +## Set budgets before writing netcode + +Derive these four numbers (ask only for what the design implies but doesn't state) and +write them down — they turn "make it fast" into a checkable target: + +1. **Max players per game session.** Drives per-client bandwidth and authority CPU. +2. **Max networked objects in scope at once** — not total objects in the world, but how + many one client must know about. This, more than player count, is what saturates + bandwidth. +3. **Tick / send rate.** The authority's fixed simulation tick, and how often state goes + out. These can differ: simulate at a high tick and send less often. For Netcode for + Entities, read the Netcode `client-server-worlds` page (`ClientServerTickRate`) + before setting them. Netcode creates that singleton with a server or host world, so + code that installs one only "if absent" silently does nothing and leaves the package + default while reading as though the budget applied — overwrite the existing + singleton on the server (or set the `NetcodeConfig` asset), and assert the value in + a test. An unasserted budget is a comment. +4. **Bandwidth ceiling per client.** Set by the weakest supported target/network. + +Don't ask the developer to supply the tick rate or bandwidth ceiling — those are what +they're asking *you* for. Propose values from the bands below, tie each to the game's +requirements, and let the developer correct them. + +State the budgets back with the recommendation, so the architecture is justified by +numbers rather than genre. If a requirement and a budget are incompatible (e.g. +hundreds of predicted physics bodies at a high tick on mobile), say so plainly and +propose which requirement to relax — see *Requirement conflicts* in +[architecture.md](architecture.md). + +## Starting bands to reason against + +**Order-of-magnitude starting points for a first proposal — not guarantees, limits, or +Unity-published figures.** Their job is to make the budget comparison executable and to +flag "this design is off by an order of magnitude" early. Every one must be replaced by +measurements from the actual game. + +| Dimension | Starting proposal | Notes | +| --- | --- | --- | +| **Tick rate — competitive action** (FPS, fighting, twitch) | **30–60 Hz** | Responsiveness and fair hit registration dominate. Above 60 is specialist territory and multiplies prediction and bandwidth cost | +| **Tick rate — co-op / casual / sandbox** | **15–30 Hz** | Usually indistinguishable to players; large CPU and bandwidth savings | +| **Tick rate — turn-based / async** | n/a | Use request/response and a backend, not a fixed netcode tick | +| **Send rate** | **at or below the tick, often 20–30 Hz** | Sending less often than you simulate is the cheapest early win; not every object needs per-tick updates | +| **Per-client bandwidth - desktop/console broadband** | **~50-150 KB/s** (about 0.4-1.2 Mbps) | Still finite: the ceiling is the worst-connected player you intend to support | +| **Per-client bandwidth - mobile cellular** | **~10-30 KB/s** (about 80-240 kbps) | Markedly tighter and metered. Also watch battery/radio wake-ups from high send rates | +| **Objects in scope where relevance filtering stops being optional** | **~100–300** | Below that, naive replication often survives; above it, interest management is the difference between shipping and not | +| **Predicted objects per client** | **~1–10** — what the player controls and directly touches | Cost is per predicted object *and* multiplied by re-simulation (below). The floor is not zero — see below | + +**Predict what the player controls when responsiveness matters.** Budget at least one +predicted ghost per player when the owner must see its own input take effect without +a round trip (why, and the remote-based alternative: *Input* in +[syncing-gameplay.md](syncing-gameplay.md)). + +How to use them: pick a band from the game's requirements, state the number you're +proposing and why, then treat the first profiling run as the thing that decides. If the +developer's target sits outside a band, that's a signal to check the design or the +requirement — not automatically a blocker. + +Verify platform-specific ceilings against current platform/certification documentation +rather than these bands, especially for console submission. + +## The levers, in order of impact + +Apply these in order, because the early ones win far more than the late ones and +micro-optimizing before relevance filtering is wasted effort. For Unity Netcode, +read each lever's page before applying it, and again if the measurement doesn't move. + +1. **Don't replicate it at all.** The cheapest object is never networked: derive + deterministic content from a shared seed, keep cosmetic objects local, and replicate + outcomes rather than intermediate steps. +2. **Relevance.** Usually the biggest saving, and an information boundary, because a + client cannot inspect state it never receives. Netcode `optimization/optimize-ghosts` + page (*Ghost relevancy*). The GhostObject bridge has no NGO-style `NetworkShow` + facade; reach relevance through the linked entity/world with an ECS relevance system. +3. **Importance.** Decides what degrades first when bandwidth saturates. Netcode + `optimization/optimize-ghosts` page (*Importance scaling*). +4. **Static optimization and send rate.** Stop resending what doesn't change and send + low-fidelity objects less often. Netcode `optimization/optimize-ghosts` page + (*Optimization Mode*) and `optimization/limit-snapshot-size` page. Lower + predicted-ghost send rates cautiously, because they trade client CPU for + misprediction (Netcode `optimization/reduce-prediction-overhead` page). +5. **Shrink the payload.** Quantize to the precision the game needs and don't replicate + values a client can derive. Netcode `optimization/compression` page. +6. **Narrow prediction scope.** Prediction is the most expensive per-object feature, so + predict what the player controls and touches and interpolate the rest. Netcode + `optimization/reduce-prediction-overhead` and `prediction-switching` pages. + Prediction switching is not available on a single-world host. +7. **Split by audience.** Send data only to the clients that use it (physics velocity + only to clients predicting that object, owner-only state only to its owner). + +A GhostObject sets some of these levers on its GhostObject component (Netcode +`ghostobject/ghostobject-replicate` page, *GhostObject settings*); for the rest, use +`Ghost.Entity`/`Ghost.World` or `GhostComponentRef`. See +[netcode-for-entities.md](netcode-for-entities.md). + +## Prediction cost + +Read the Netcode `prediction-n4e` page for rollback and re-simulation before budgeting +predicted logic. Budget **re-simulation as RTT x tick rate**, and scale the page's +example figure to the game's own tick rate rather than reusing it. + +Consequences to design around: + +- Keep predicted logic lean; heavy work does not belong in the prediction loop. +- Predicted physics multiplies this cost — budget it explicitly for physics-heavy + competitive games (Netcode `optimization/reduce-prediction-overhead` page). +- Predicted logic must be **idempotent with respect to restored state** across repeated + ticks, or it produces jitter and mispredictions on its own. Determinism is not + sufficient: rollback restores only `[GhostField]`-serialized data, so a + read-modify-write on storage it does not restore is perfectly deterministic and still + compounds once per replayed tick. See *Prediction and replay* in + [syncing-gameplay.md](syncing-gameplay.md). +- Cost scales with RTT, so a build that feels fine on LAN can fall apart at real latency. +- A single-world host is never replayed, so host-side profiling understates prediction + cost — and host-side testing cannot see prediction defects at all. Measure on a real + client process. +- Partial snapshots can roll back interacting predicted ghosts to different ticks. + Read the Netcode `prediction-details` page for the options before choosing one, and + measure the added CPU and prediction-history memory cost of the fix. + +## How to test — the measurement loop + +**This is the canonical testing guidance for the whole skill.** Recommend this loop +rather than asserting a design is fast: + +1. **Profile the network**, not just the frame time. Use Unity's multiplayer profiling + tools to see per-object bandwidth and message volume, and identify which objects + dominate the budget. +2. **Simulate real conditions, from the start.** Add latency, jitter, and packet loss + with the in-Editor emulator in the Multiplayer Play Mode clones, never on a clean + LAN alone, which hides the problems prediction exists to solve; a buffer or timeout + tuned on LAN will be wrong in the field. Set them on each clone with + `netcode.simulator set` (Unity Netcode) or `netcode.gameobjects.simulator set` + (NGO); see *Network conditions in clones* in + [multiplayer-play-mode.md](multiplayer-play-mode.md), and read the emulator page + it names before configuring it. Confirm the measured RTT rose before trusting the run. + In final testing, also run over the actual transport/Relay path and on target + devices. The Netcode emulator works only in development builds; a release build + silently ignores its settings and `--loadNetworkSimulatorJsonFile`, so use OS-level + tools there as the NGO page describes. +3. **Compare against the budgets** above. Name the top consumer. +4. **Apply the highest lever that addresses it** and re-measure. +5. **Stop after about three iterations** without meaningful improvement and tell the developer + what's structurally limiting - an architecture problem (wrong topology, too many + predicted bodies, no relevance filtering) will not yield to further tuning. + +Use Multiplayer Play Mode, with the emulator on, as the working loop for function and +for behaviour under latency. Editor profiling numbers are indicative; take the final +performance numbers from development builds on target hardware in final testing (see the +verification gate's *Final testing* section). Connecting +successfully is not "done" — also run the unhappy-path checklist in +[netcode-lifecycle.md](netcode-lifecycle.md) under these same adverse conditions. + +## Verifying prediction + +If the project predicts anything, verify prediction **in two processes**: + +- a second process on a non-loopback address — a Multiplayer Play Mode clone joining + the main Editor by default, with the emulator adding latency; +- input driven on the clone by `script eval` calls to the game's own gameplay + methods (no command injects input into a clone), so no input-injection code goes + into the game; +- each peer's **rendered** value compared against its **replicated** value, read + with `netcode.ghost get` on each instance several times over enough ticks for drift + to show, not through added logging. + +When the comparison diverges, find the first system that introduced it with the tool +on the Netcode `testing/prediction-tracing-tool` page. Read its requirements first: +it needs separate client and server worlds in one process, so it cannot trace a +single-world host. + +A single-world host (the default) is never replayed, so single-process tests only +ever take the authority path — see *Single-world details* in [architecture.md](architecture.md). +Divergence that grows with time, or a predicted value saturating asymmetrically +at a clamp limit, means accumulation into unrestored storage — see *Prediction +and replay* in [syncing-gameplay.md](syncing-gameplay.md). + +## Common causes of slow multiplayer + +Check these before anything exotic: + +- **No relevance filtering** - every client receives the whole world. +- **Everything predicted** - prediction applied to objects the player never touches. +- **Replicating full transforms every tick** for objects that barely move, or that could + be driven locally. +- **Replicating derived or cosmetic state** (animation/VFX detail) instead of the event + that caused it. +- **Per-tick RPC/event spam** where replicated state (or a batched event) would do. +- **Unquantized, unbounded payloads** - large structs, strings, or collections + replicated wholesale. +- **Tick/send rate set higher than the game needs**, applied globally. +- **Only tested on LAN**, so latency-dependent cost was never observed. +- **Networking objects that could be deterministic** from a seed or shared config. diff --git a/skills/build-multiplayer-game/references/session-connectors.md b/skills/build-multiplayer-game/references/session-connectors.md new file mode 100644 index 0000000..bde1084 --- /dev/null +++ b/skills/build-multiplayer-game/references/session-connectors.md @@ -0,0 +1,131 @@ +# Session connectors + +Links in this file resolve to the skill directory's `references/` folder, the folder this file is in. Project and package paths in code spans are relative to the user's project or the package root. + +The session authoring components run the create and join flows without session code: a `MultiplayerSession` +asset holds the live session, a `SessionConnector` asset performs one operation (`Create`, `Join` by code or +id, or `CreateOrJoin`), and a `SessionConnectorBehaviour` runs it when the player signs in or when the game +calls `Execute()`. Read [Create sessions in the Editor](https://docs.unity.com/en-us/mps-sdk/scriptableobject-sessions.md) +before setting them up. + +Use the Session API instead when any of these holds: + +- The stack is GhostObject (see [Network](#network)). +- Step 3 chose distributed authority or host migration, because a connector starts only a None, Direct or Relay + network and sets no host migration. +- The flow has no gameplay netcode (a lobby or a metadata-only session), because a connector's network starts + netcode. +- The user asked for code. +- The project's session code already runs the flow, because a connector next to that code creates or joins a + second session. + +## Contents + +- [Set up](#set-up) +- [Wire the UI](#wire-the-ui) +- [Network](#network) +- [Dedicated server](#dedicated-server) +- [Verify](#verify) + +## Set up + +On the main Editor, in Edit Mode. List each group first (`unity command services.core`, `services.authentication`, +`services.multiplayer`), because the commands depend on the installed package versions. Search the project's +code first: skip `add_services_initialization_component` when it already calls `UnityServices.InitializeAsync`, +and `add_player_authentication_component` when it already signs the player in (an `AuthenticationService` sign-in +call, or a `PlayerAuthentication` component in a scene), because signing in twice fails: + +```bash +unity command services.core add_services_initialization_component # initializes Unity Services in Play Mode +unity command services.authentication add_player_authentication_component # signs the player in anonymously +unity command services.multiplayer create_session_handle --path Assets/Multiplayer/Session +unity command services.multiplayer create_session_connector --path Assets/Multiplayer/Host --connector-type Create --multiplayer-session Assets/Multiplayer/Session +unity command services.multiplayer create_session_connector --path Assets/Multiplayer/Join --connector-type Join --multiplayer-session Assets/Multiplayer/Session +unity command services.multiplayer configure_session_connector --path Assets/Multiplayer/Host --network Relay # saves the asset +unity command services.multiplayer add_session_connector_behaviour --game-object "Host Game" --session-connector Assets/Multiplayer/Host +unity command services.multiplayer add_session_connector_behaviour --game-object "Join Game" --session-connector Assets/Multiplayer/Join +unity command scene save # the two component commands leave the scene unsaved +``` + +`create_session_connector` always makes a new asset, so a second run on the same path adds `Host 1.asset`. +Change an existing connector with `configure_session_connector`, which sets only the arguments given. A +`CreateOrJoin` connector needs `configure_session_connector --session-id `. Never give a Join connector a +`--join-code`, because the game sets the code at join time (see [Wire the UI](#wire-the-ui)). + +If a group lacks its command, the installed package predates it: + +- No `add_services_initialization_component` or `add_player_authentication_component`: add + `Unity.Services.Core.Components.ServicesInitialization` and + `Unity.Services.Authentication.Components.PlayerAuthentication` with `component add`, set the latter's + `SignInAnonymously` to `true` with `component set_field` (it defaults to `false`), then `scene save`. +- No `configure_session_connector`: set the network as [Network](#network) says. Use the Session API for a + `CreateOrJoin` flow, because its session id then has no command. +- No `create_session_connector`: use the Session API instead (step 4 of the skill), because the connector's + settings live on an asset and `component set_field` does not write assets to disk, so Multiplayer Play Mode + clones would not see them. + +## Wire the UI + +- Leave **Execute On Sign In** off for anything a button starts, and call the behaviour's `Execute()` from the + button: a UGUI `Button.onClick` entry in the Inspector, or `button.clicked += hostBehaviour.Execute;` in the + UI Toolkit screen's controller. +- Join by code: set the code on the connector right before every `Execute()`, with + `joinBehaviour.SessionConnector.WithJoinByCode(codeField.value)`. Never rely on a code already on the asset, + because a connector keeps its settings when Play Mode exits, so it holds whatever code was set last. +- React to the result through the connector's `SuccessfulExecution` (the `ISession`: show `Code` to the host, + switch screens) and `FailedExecution` (the error message), in the Inspector or in code. +- Turn **Execute On Sign In** on only for a flow with no button, such as a `CreateOrJoin` connector that puts + every tester in one session. + +## Network + +A connector's network starts the netcode stack through the default network handler, so use connectors only +where step 4 of the skill gives start-up to the default handler (NGO, direct ECS ghosts). A GhostObject game +uses the Session API. + +A new connector's network is Direct on `127.0.0.1`: it connects Multiplayer Play Mode instances on one machine +and nothing else. For players on different networks, configure the Host connector with `--network Relay`, as +[Set up](#set-up) does. Relay also connects Multiplayer Play Mode instances, so keep it for local testing. + +When the group has no `configure_session_connector`, set the network with +`component set_field --target Assets/Multiplayer/Host.asset --field m_SessionNetworkSettings.m_Network --value '"Relay"'`, +then save it with `unity command script eval --code "UnityEditor.AssetDatabase.SaveAssets(); return true;"`, +because `set_field` leaves the asset changed only in memory. + +## Dedicated server + +The server counterpart creates the session when a dedicated server starts: a `ServerSessionConnector` asset +creates it, publishes the connector's session properties (for example the ones clients quick-join against) and +starts its Direct or Relay network, and a `ServerSessionConnectorBehaviour` runs it once the server is +authorized. It only creates sessions; backfill and sessions allocated by the Matchmaker stay on +`MultiplayerServerService` ([dgs-entrypoint.md](dgs-entrypoint.md)). + +```bash +unity command services.multiplayer create_session_handle --path Assets/Multiplayer/ServerSession +unity command services.multiplayer create_server_session_connector --path Assets/Multiplayer/Server --multiplayer-session Assets/Multiplayer/ServerSession +unity command services.multiplayer add_server_session_connector_behaviour --game-object "Server Session" --session-connector Assets/Multiplayer/Server # runs on authorization by default +``` + +- The behaviour never signs the server in. Sign in from server code, with `SignInFromServerAsync` on a hosted + server, or `SignInWithServiceAccountAsync` with a service account allowed to create sessions on a local or CI + server. Read the key and secret from environment variables that the host or CI secret store sets, never + from command-line arguments, because shell history and process listings expose those. Never put them in a + serialized asset or in source, because those ship in builds. +- It acts only where the multiplayer role includes Server: a Dedicated Server build, or an instance Multiplayer + Roles doesn't mark Client only. Without the Multiplayer Roles API (Unity 6000.5 or older without the + Dedicated Server package) every instance acts, so keep the behaviour out of client scenes there. +- A new server connector's Direct network listens on all interfaces and publishes this machine's first LAN + address, which reaches the local network only. For internet hosting, set the publish address to the server's + public or allocated address in the connector's network settings. +- To accept players only once the game server is ready, set the connector's network type to None and call the + behaviour's `StartNetwork()` when ready (`StopNetwork()` to close it). +- Clients find the session through the Session API (quick join filters on the published properties) or a Join + connector with the session id. + +## Verify + +Verify in Multiplayer Play Mode per [multiplayer-play-mode.md](multiplayer-play-mode.md): a game whose flows run +on connectors needs no test hook class. `run_session_connector` runs a behaviour's connector on an instance in +Play Mode and returns the session. Its `--join-code`, `--join-session-id` and `--session-id` are set on the +connector first, as a button sets them, so pass the code on every join run. It raises the connector's +`SuccessfulExecution` and `FailedExecution`, so the game's own listeners react as they would to a button. diff --git a/skills/build-multiplayer-game/references/syncing-gameplay.md b/skills/build-multiplayer-game/references/syncing-gameplay.md new file mode 100644 index 0000000..786980b --- /dev/null +++ b/skills/build-multiplayer-game/references/syncing-gameplay.md @@ -0,0 +1,316 @@ +# Syncing gameplay + +## Contents + +- [Decide each value](#decide-each-value) +- [GhostObject state](#ghostobject-state) +- [Direct ECS state](#direct-ecs-state) +- [Input](#input) +- [Prediction and replay](#prediction-and-replay) +- [Remotes and RPCs](#remotes-and-rpcs) +- [Transforms](#transforms) +- [Physics and collision](#physics-and-collision) +- [Animation and presentation](#animation-and-presentation) +- [References and collections](#references-and-collections) +- [Time and smoothing](#time-and-smoothing) +- [Retrofitting a single-process game](#retrofitting-a-single-process-game) +- [Common object plan](#common-object-plan) + +Use this reference to decide what each gameplay object sends and how it behaves +between authoritative updates. Verify the API names below against the installed +`com.unity.netcode` package before generating code. Where the +package's manual text and its code disagree on a name, trust `Runtime/` and the +compiled samples in `Tests/Editor/DocCodeSamples/`, because those are what compiles. + +Links in this file resolve to the skill directory's `references/` folder, the folder this file is in. Project and package paths in code spans are relative to the user's project or the package root. + +## Decide each value + +Ask in order: + +1. Can every peer derive it from existing state, an event, or a shared seed? Keep + it local. +2. Who is the sole authority? Only that side writes the canonical value. +3. Does a late joiner need it? Use replicated state if yes, a remote/RPC if no. +4. What is the smallest useful representation? Prefer input, enum, ID, bounded + collection, or quantized value over a full object or transform. +5. Who needs it, and how often? Apply relevance, importance, and send-rate limits. + +## GhostObject state + +Before writing a `GhostBehaviour`, read the Netcode `ghostobject/ghostobject-replicate` +page (`GhostField`, accepted types, `FieldConfig`), the +`ghostobject/ghostobject-prediction` page (prediction methods, `CanWriteState`, +`TickedDeltaTime`) and the `ghostobject/ghostobject-hybrid` page (`Ghost.Entity`, +`GhostComponentRef`, jobs). Read them again if generated code fails to compile. +Then apply these rules, which the pages don't state or that are easy to get wrong: + +- Declare every `GhostBehaviour` in its own file named after the class, because + Unity binds a MonoBehaviour to its script by file name. A namespace is + recommended but not required. Never name a namespace segment `Netcode`, because + `Netcode` then resolves to that namespace in it and in every namespace that + contains it, so one such file breaks `Netcode.` calls in other files too. +- `CanWriteState` is true when the ghost entity has `PredictedGhost`, which reads + as "false for a ghost that is never predicted" — it is not. For `GhostModeMask.Interpolated` the + package strips `PredictedGhost` on clients and **retains it on the server**, so + `CanWriteState` is true on the server and false on every client, + `PredictionUpdate` is the correct server write path even for an + interpolated-only ghost, and clients are structurally incapable of writing it. + An all-interpolated design is implementable and gets the single-writer + invariant enforced by the package rather than by discipline. On a single-world + host `CanWriteState` is true as well, which is why mirror code needs separate + gating — see *Single-world details* in [architecture.md](architecture.md). +- For a struct `GhostField` or a `GhostComponentRef`, copy the value, mutate + the copy, and assign it back, because a change to the copy is never applied. +- Compile a minimal `GhostBehaviour` first. Before treating a source-generation + failure as a package defect, bisect it to the smallest declaration that still + fails; a failure that disappears is a project bug, not a reason to fall back. + +## Direct ECS state + +Read the Netcode `ghosts` and `ghost-types-templates` pages for `[GhostField]`, +`[GhostComponent]` and quantization before authoring direct ghost components. +Quantize every replicated value to gameplay precision, because unneeded bits cost +bandwidth on every snapshot. + +## Input + +Before modelling player input, read the Netcode `command-stream` page for direct +ghosts, or the `ghostobject/ghostobject-prediction` page (`GhostInput`, +`PredictionGatherInput`, reading past input) for a `GhostBehaviour`. Capture +GhostObject input only in `PredictionGatherInput`, because Netcode overwrites the +input struct right before that method in full-ticks-only mode or with forced input +latency. + +**`PredictionGatherInput` runs once per rendered frame, not once per simulation tick.** +`GhostInputSystemGroup` sits in `SimulationSystemGroup`, outside the prediction +loop, so at 60 fps with a 20 Hz tick it fires about three times per tick — and +for an ordinary field only the last write for a tick survives. Choose the +representation per field: + +| Input shape | Representation | Why | +| --- | --- | --- | +| Continuous axis (stick, mouse look) | plain field | The last value *is* the current value; dropping older samples is correct | +| One-shot action (jump, fire, ability) | `InputEvent` | Netcode counts these rather than overwriting, so a press on any frame of the tick survives | +| Counted increments (discrete aim steps, scroll notches) | plain field, **coalesced per tick** | Neither last-write nor `InputEvent` preserves a sum: accumulate a running total keyed on `NetworkTime.InputTargetTick` and write the total each frame | + +This table is for GhostObject `GhostInput`, whose `PrepareToCapture()` starts from +`default`. Direct ECS input components keep the previous frame's values, so +incremental values sum across frames there (Netcode `command-stream` page). + +Writing each sample straight into a plain field silently discards most of a +discrete input stream — a responsiveness bug that no test flags and that players +feel without being able to describe. If the sampling function *consumes* state +(an auto-repeat accumulator, a "pressed since last poll" latch), a discarded +sample is gone permanently: coalesce, never overwrite. + +**Make a ghost that gathers input through `PredictionGatherInput` `Predicted` or +`OwnerPredicted` when the owner must see the result without a round trip.** The input +callback runs for owned ghosts with `GhostOwner`, `GhostOwnerIsLocal` and +`AutoCommandTarget`, and the code sends that input for interpolated ghosts too, but +the owner then sees its own actions only after the server's snapshot returns. The +Netcode `command-stream` page describes command targets as predicted, so run any +interpolated-only input design in Play mode and confirm the server receives the input +before building on it. The +alternative is to send intent as a **rate-limited remote** and keep the ghost +interpolated; that is a real design, but per-tick remotes are an anti-pattern +where replicated state would do. + +## Prediction and replay + +The client re-runs the prediction loop for several ticks per rendered frame and +re-presents the same input on each replayed tick. Before each replay netcode +restores **only** `[GhostField]`-serialized data; plain MonoBehaviour fields, +statics, and any component without ghost fields are explicitly *preserved*, not +rewound. + +So the contract governs *where you write from*, but replay safety is decided by +*which storage you mutate*. A predicted value must satisfy: the value after +replaying tick T any number of times equals the value after applying tick T once +to the restored value. The required property is **idempotence with respect to +restored state**, not determinism — a read-modify-write on unrestored storage is +perfectly deterministic and still compounds once per replay. + +- **Accumulate into the `GhostField` itself.** + `Field.Value = Clamp(Field.Value + input.delta)` is replay-safe; + `local += input.delta; Field.Value = local;` drifts, because `local` survives + the rollback that resets `Field`. +- **Do not gate accumulation with `IsFirstTimeFullyPredictingTick`.** That flag + is for one-shot side effects — spawns, VFX, audio. Replayed ticks *must* + re-apply their delta on top of the restored value; suppressing it throws the + prediction away and trades drifting input for laggy input. +- If the authority and a predicted client genuinely need different accumulators — + the server is never replayed, so it may safely accumulate on its own object — + split the two paths explicitly and say why in a comment. One writer per role. + +Symptoms: divergence that grows with time, an owner's rendered value running +ahead of the authoritative one, or a predicted value saturating asymmetrically at +a clamp limit. None of these are visible in a single process, because a host is +never replayed. + +## Remotes and RPCs + +Read the Netcode `ghostobject/ghostobject-rpcs` page (RPC methods, custom messages, +targeting, polling versus automatic handling) before declaring a GhostObject remote, +and the `rpcs` page for direct ECS `IRpcCommand` in systems and jobs or when you +need targeting the GhostObject API doesn't expose. Then: + +- On a single-world host a `ServerToClient` remote also dispatches into the + host's own handler. Gate any handler with a visible or stateful side effect on + `IsServer`, never on `IsClient` (true on that host). Full rule: *Single-world + details* in [architecture.md](architecture.md). +- Treat client-to-server calls as requests and validate sender, ownership, rate, + range, and resources. +- Do not send remotes every tick or use them to initialize persistent state, because + replicated state already covers both and a late joiner never receives a past remote. + +## Transforms + +Read the Netcode `ghostobject/ghostobject-prediction` page (*Read the tick-accurate +transform*, *Parent a ghost under another ghost*) and the +`ghostobject/ghostobject-hybrid` page (nested GhostObjects, scale) before writing +transform or attachment code. Then: + +- Do not let a normal `Update` script and the prediction loop both write the same + replicated value, because the two writers fight and the result corrects every + tick. This applies to any ghost-backed state, not just the transform. +- Replicate relationships for attachments and derive child transforms locally. Make + each attachment its own ghost with **Parent Replication** enabled on its prefab. + Set that option in the Inspector only, because the property is read-only from + code. Otherwise flatten network identity or use direct ECS. +- Enable **Uniform Scale** on a GhostObject that never scales per-axis, because + GhostObjects replicate per-axis scale by default. Direct ECS ghost prefabs + replicate non-uniform scale only if they opt into `PostTransformMatrix3DScaleVariant`. + +## Physics and collision + +- The authority decides collisions, hits, damage, and resulting state. A client + can predict feedback but cannot report a trusted outcome. +- Collider geometry comes from matching content; replicate enabled/hitbox state, + not collider shapes. Verify server builds preserve gameplay collision content. +- Predict only player-controlled or directly interacted bodies. Keep cosmetic + debris, cloth, and ragdolls local; with GhostObjects, put those bodies in a + separate `LocalPhysicsMode.Physics3D` scene, because Netcode re-simulates the + whole default physics scene on every replayed tick. +- Stamp actions with network ticks. For lag compensation, retain bounded collision + history and validate against the client's tick, never an unbounded client time. + +For GameObject physics, read the Netcode `ghostobject/ghostobject-physics` page +(Rigidbody Replication, recommended physics settings, guarding physics messages +against replay). Disabling **Rigidbody Replication** doesn't take a dynamic body out +of replay: Netcode still resimulates it without rolling it back, so put bodies that +must not be predicted in the separate physics scene above. Use GameObject predicted +physics only after a focused prototype under latency. For +direct ECS predicted physics, the more mature advanced path, read the Netcode +`physics` page. + +## Animation and presentation + +Don't look for an animator replication component for GhostObjects: +`GhostAnimationController` serves entity-ghost presentation objects only. +Replicate animation causes: + +- movement speed, grounded state, stance, aim angle, and gameplay phase as compact + state; +- fire, hit reaction, and emote as one-shot remotes/events; +- animator graph, blending, IK, procedural motion, VFX, audio, camera, and screen + effects locally. + +Avoid root motion owning a predicted transform. Gameplay movement should drive +the canonical transform and animation should follow it. + +Gate irreversible presentation triggered from prediction with +`IsFirstTimeFullyPredictingTick` (Netcode `ghostobject/ghostobject-prediction` page) +or emit it from a confirmed state transition. Never use that gate on accumulated or +continuous predicted state; see *Prediction and replay* above. + +## References and collections + +Do not replicate managed object references. Use stable ghost identity or an ECS +entity reference supported by the serializer and handle targets that have not +spawned yet or have despawned. Never cache a resolved instance across despawn and +respawn without revalidation. + +Bound collections and prefer per-element deltas. IDs/enums beat strings. Version +custom payloads when client and server builds can differ. Large payloads fragment, +stall, or fail; split them or avoid replication. + +"Bound collections" is not a license to reach for a container type: read the +Netcode `ghost-types-templates` page for the types and capacity limits the installed +generator accepts, then compile a minimal `GhostField` declaration of that type on +a `GhostBehaviour` before designing around it, because the GhostObject generator can +reject a type the page lists. + +**Entity-per-fact.** For a bounded, append-only collection — craters, placed +structures, scored hits — prefer one small ghost per element over a list on a +singleton ghost: + +- it keeps the data as replicated *state*, so late join is correct without + replaying events; +- each element is immutable after spawn, so static optimization stops resending + it; +- it sidesteps container-type limits entirely; and +- ordering, where replay order matters, becomes an explicit `Sequence` field + rather than an implicit list index — which also survives the fact that + `GhostField` is eventually consistent and may skip intermediate values. + +Bound it by policy and state the cap. A few dozen tiny static ghosts sit far +below the threshold where relevance filtering starts to matter. + +## Time and smoothing + +Drive simulation from network ticks and the ticked delta time (*Access time* on the +Netcode `ghostobject/ghostobject-prediction` page), never wall-clock time or frame +counts, because those differ per peer. Replicate an authoritative end tick, not a +countdown every frame. + +Interpolate remote objects; predict owned or directly interactive objects. Smooth +visual corrections without feeding smoothed presentation back into simulation. +Constant correction indicates nondeterminism, mismatched content, or competing +writers, not a smoothing problem. + +## Retrofitting a single-process game + +A game that already runs locally has a pre-existing input path and pre-existing +writers for every value that is about to become replicated. That is where retrofit +defects live, and the framing in the rest of this file — `IsServer`, +`IsClient`, `CanWriteState` — pushes toward server-versus-client thinking when +the question that matters is *local play versus game session active*. + +- **Audit every writer.** For each value that becomes replicated, list every + existing site that writes it. Legacy sites must be disabled when a game session is + active, not merely when the local peer is a client. +- **Use the right predicate.** "Am I the authority?" is true for local play *and* + for the host, so it is exactly the wrong distinction. The predicate that gates + legacy input is "is there **no** game session". Getting this wrong lets the host's + keyboard drive another player's avatar — and because the host is the authority, + that replicates. +- **Keep the local mode on its original path.** A local/hotseat mode that creates + no worlds is the cheapest regression guard available: the pre-existing test suite + keeps passing through the whole migration. +- **Watch for double sampling.** If a legacy poll and `PredictionGatherInput` both run, a + consuming input function is called twice per frame and every hold/repeat timing + is wrong — see *Input* above. + +## Common object plan + +| Object | Replicate | Keep local | +| --- | --- | --- | +| Server-authoritative player | Input; authoritative transform/state; compact animation drivers | Animator, IK, VFX/SFX | +| Trusted owner-driven player | Input or owner-predicted state, validated where needed | Presentation | +| Deterministic projectile | Spawn parameters/seed and authoritative hit result | Flight trail and cosmetic flight simulation | +| Gameplay physics prop | Authoritative thresholded/quantized state | Impact presentation | +| Cosmetic debris/ragdoll | Trigger only | Entire simulation | +| Door/container | Open/content state | Motion and audio | +| Static/procedural world | Nothing, or seed/parameters | Geometry/result | +| Score/phase/timer | Authoritative state and end tick | UI | + +On a single-world host, "replicate the cause, derive the visual locally" — the +deterministic-projectile row above, and the same advice in +the lifecycle reference — needs one extra guard. +The host receives its own server-to-client spawn event and it already owns the +authoritative object, so gate the local derivation on `IsServer` and let the +mirror run only on peers that lack the authoritative instance. The same applies to +the authoritative hit result: if applying it mutates shared simulation state such +as terrain, applying it twice on the host **desynchronizes the peers** rather than +merely drawing twice. diff --git a/skills/setup-multiplayer-services/references/underlying-services.md b/skills/build-multiplayer-game/references/underlying-services.md similarity index 90% rename from skills/setup-multiplayer-services/references/underlying-services.md rename to skills/build-multiplayer-game/references/underlying-services.md index 272c5df..cd4ed82 100644 --- a/skills/setup-multiplayer-services/references/underlying-services.md +++ b/skills/build-multiplayer-game/references/underlying-services.md @@ -1,4 +1,4 @@ -## Underlying services (use only when necessary) +# Underlying services (use only when necessary) **Agent-only reference** for implementation when the primary API is insufficient or the user explicitly requested these—**do not** surface this table or product names to the user unless they asked for them. @@ -8,4 +8,4 @@ Summarized for reference—not the default path: |------|-----------|------| | **Lobby** | `Unity.Services.Lobbies` | Standalone lobby CRUD, query, realtime lobby events, migration payloads—prefer **Sessions** unless you need lobby-only workflows. | | **Matchmaker** | `Unity.Services.Matchmaker` | Low-level tickets, backfill ticket APIs, ticket status—prefer **`MatchmakeSessionAsync`** + **`MatchmakerOptions`** on **`IMultiplayerService`** first. | -| **Relay** | `Unity.Services.Relay` | Raw allocations and join codes—prefer **`WithRelayNetwork`** / **`StartRelayNetworkAsync`** on the session network first. | \ No newline at end of file +| **Relay** | `Unity.Services.Relay` | Raw allocations and join codes—prefer **`WithRelayNetwork`** / **`StartRelayNetworkAsync`** on the session network first. | diff --git a/skills/build-multiplayer-game/references/verification-gate.md b/skills/build-multiplayer-game/references/verification-gate.md new file mode 100644 index 0000000..617aeb0 --- /dev/null +++ b/skills/build-multiplayer-game/references/verification-gate.md @@ -0,0 +1,185 @@ +# Verification gate + +## Contents + +- [Hard implementation gate](#hard-implementation-gate) +- [Verify in this order](#verify-in-this-order) +- [Completion check](#completion-check) + +Links in this file resolve to the skill directory's `references/` folder, the folder this file is in. Project and package paths in code spans are relative to the user's project or the package root. + +## Hard implementation gate + +For a new realtime multiplayer project, the primary implementation is NGO or Netcode +for Entities, chosen per [choosing-netcode.md](choosing-netcode.md). Do not implement +Mirror, a raw `NetworkDriver` gameplay protocol, or any other networking runtime unless +the user requires it. Before writing any gameplay networking code, record all of +the following in the project (README or a `NETWORKING.md` decision record), each item +citing its source file with quoted lines, not assertions. Items 2, 4 and 6 apply to +Unity Netcode only; NGO skips them and takes item 5's NGO branch. + +1. Installed Unity, the chosen netcode package (`com.unity.netcode` or + `com.unity.netcode.gameobjects`), and `com.unity.transport` versions, quoted + from `ProjectSettings/ProjectVersion.txt`, `Packages/manifest.json`, and + `Packages/packages-lock.json`. +2. The authoring-layer APIs you will use (`GhostObject`, `GhostBehaviour`, + `GhostField`, or the direct ECS types), each confirmed in the installed + package source with the grepped path. +3. The selected stack, topology and authority model, and the requirement that decided + the stack. +4. For every predicted value, **the restored storage it lives in**: the + `GhostField`/`[GhostField]`-carrying component that rollback rewinds. A row + naming a plain MonoBehaviour field, a static, or a component with no ghost fields + is a defect before it is written (see *Prediction and replay* in + [syncing-gameplay.md](syncing-gameplay.md)); an unfilled row means the + value is not yet designed. +5. A minimal probe of **the authoring path that was chosen**, run in Play mode (a + Multiplayer Play Mode scenario; a development build only when MPPM is unavailable), + with command output as its evidence. The chosen stack and authoring layer pick the branch: + - *GameObject authoring* (GhostObject): the compile + probe's exact compiler output recorded (delete the probe afterwards), plus a runtime + probe: game-session start, registered-prefab spawn, one `GhostField` read. + - *Direct ECS authoring* (an ECS-native project, or an installed package with no GhostObject layer): the + equivalent runtime probe: game-session start, spawn of a `GhostAuthoringComponent` + prefab, one `[GhostField]` read. Equivalent evidence, not a lighter bar: + recorded compiler output for an absent `GhostObject` is not a probe of the path + being implemented. + - *NGO*: game-session start, spawn of a `NetworkObject` prefab registered with the + `NetworkManager`, one `NetworkVariable` read. + + Read the field with `netcode.ghost get` (Unity Netcode) or `script eval` + (NGO, because `get_object` doesn't show `NetworkVariable` values), and run the stack's `audit` + command before the probe. A compile-only probe does not validate initialization or + lifecycle on any branch. +6. Either a GhostObject/GhostBehaviour implementation, or a documented direct-ECS path + naming what routed the project there: an absent GameObject authoring layer, a + reproduced GhostObject defect, an unimplementable requirement, or an ECS-native + project chosen up front. + +If any item is missing, stop and ask for approval before implementing. Approval may only +select a stack per [choosing-netcode.md](choosing-netcode.md), a path in the +[ghost authoring fallback order](ghost-authoring.md), or record an explicit user requirement +for raw Transport. Do not substitute raw Unity Transport because it is smaller, stable, +or more convenient. + +Every cited verification output must postdate the newest source file it claims to verify; +record every failed or truncated verification attempt alongside the successful one. +Every design claim in the record (tick and snapshot rates, replicated fields, lifecycle +behavior) must name the config field or code symbol that implements it, and every +numeric budget must be asserted in a test; see the `ClientServerTickRate` trap in +[performance-and-scale.md](performance-and-scale.md). + +Before multiplayer testing, verify Run in Background is enabled, or that focus loss is +deliberately handled, per *Start and connect* in +[netcode-lifecycle.md](netcode-lifecycle.md). + +## Verify in this order + +Write gameplay code only after the design is agreed. + +- **Agreement.** "Agreed" means the final report has been emitted with its package-probe + fields filled from the gate's cited file evidence. A straightforward trusted-game-session + default needs no explicit user reply; cheat-sensitive or ranked designs require + explicit user approval. +- **Probe outcome routes the fallback.** A failed GhostObject probe, or an absent layer, + moves a new project to direct ECS ghosts (and to the direct-ECS branch of item 5), not + to NGO, because the requirement that chose Unity Netcode still holds. +- **Function across processes, in Multiplayer Play Mode.** Verify gameplay with a + scripted host-plus-client scenario via [multiplayer-play-mode.md](multiplayer-play-mode.md): + the main Editor hosts and a virtual player joins. This is the default; it needs no build. +- **Cross-process connect on a real address.** The minimal connectivity probe must + include a connect from a second process, with evidence for the chosen stack: + - *Unity Netcode:* the client's driver-selection lines quoted from its log (a + virtual player's console, or Player.log). Those lines are Debug-level, so set the + clone's Netcode log level to Debug before the run (`netcode.debug set_log_level`); + at the default level their absence proves nothing. Quote the clone's + `netcode get_connection_state` output alongside them. Whenever a non-host ServerWorld + exists in the client's process (binary-worlds `ClientAndServer`), the default + bootstrap plus driver constructor otherwise routes "remote" connects to the + in-process IPC loopback, with only a warning (`IPC interfaces only support loopback + address`) in the log (see *World creation and transport driver selection* in + [netcode-lifecycle.md](netcode-lifecycle.md)). A virtual player joining the main + Editor qualifies when the clone has no server world of its own: the IPC driver + cannot cross a process boundary, so a cross-process connect that succeeds used the + socket driver. A relay connect already dials a non-loopback address; for a direct + connect, use the machine's LAN address, not loopback. + - *NGO:* quote the clone's `netcode.gameobjects status` (`isConnectedClient: true`, its + `localClientId` and transport) and the host's `netcode.gameobjects list_clients` + showing that client with an RTT. NGO's transport has no in-process IPC driver, so a + client the host lists from another process connected over the network. For a direct + connect, use the machine's LAN address; a Relay connect shows `RelayUnityTransport`. +- **Test under adversity, also in Multiplayer Play Mode.** Run the clones under latency, + jitter, and packet loss with the in-Editor emulator throughout development, not in a + late pass: `netcode.simulator set` on each clone for Unity Netcode, or + `netcode.gameobjects.simulator set` for NGO (see *Network conditions in clones* in + [multiplayer-play-mode.md](multiplayer-play-mode.md) and + [performance-and-scale.md](performance-and-scale.md)). Editor profiling numbers are + indicative; final numbers come from final testing. +- **A complete game session, not a few seconds of motion.** The start signal reaches every + client (control unlocks everywhere), interactions between participants show on every + screen, and the game session ends with the same result everywhere. A participant that never + leaves the start is the classic sign that an authoritative lifecycle event was applied + locally on the host and never replicated. +- **Final testing: player builds.** Build players once the work passes in Multiplayer Play + Mode, and only for what Editor clones cannot show, because the MPPM and NGO docs place + builds there and they are slow to iterate on: server-only (`UNITY_SERVER`) code, + build stripping and the scene list, target platforms and devices, release-build + network conditions, a multi-machine run over the real transport or Relay path, + rejection of a mismatched build, and any shippable build the user asked for. With MPPM + available, add the builds to the scenario as local instances + (`add_player --type local`), per [multiplayer-play-mode.md](multiplayer-play-mode.md). + Report whatever final testing was not run as a gap, not as a failure of the change. +- **MPPM unavailable.** When MPPM is not installed or its clone never launches, build + and launch standalone host and client players by hand instead, outside any scenario, + per [multiplayer-play-mode.md](multiplayer-play-mode.md). + +## Completion check + +Before declaring the implementation done, check the following. For a ghost or NGO implementation, all of them apply. For session-only work (no gameplay +network), skip items 1, 2, 4 and 7, because they need a netcode stack or a gameplay event, and cover +item 3's evidence with the session create, join and read-back, each read with +`script eval` on the creating and joining instances, which are separate MPPM players, not +two identities in one process. + +1. `Packages/manifest.json` contains the chosen netcode package: `com.unity.netcode` + or `com.unity.netcode.gameobjects`. +2. A grep of `Assets` hits the chosen stack's types (`GhostBehaviour`, `GhostObject`, + `GhostAuthoringComponent`, `[GhostField]`, or `GhostPrefabCreation` for Netcode for + Entities; `NetworkBehaviour`, `NetworkObject` or `NetworkVariable` for NGO), and at least one matched type is reachable + at runtime (referenced by a scene, prefab, or SubScene, or an auto-registered + system/bootstrap that executes). Orphaned authoring classes and compile-only probes + do not count. +3. Runtime evidence exists: a game session (host start, a cross-process client + connect, **and at least one gameplay event (spawn, shot, impact, score change) + driven across that already-connected game session**) shown by command output from + each process (connection state per *Cross-process connect on a real address* above, and the event's + state read with the commands in item 4), quoted in the decision record and run after + the last source change. Don't add logging to produce it. A connect-only check, a solo + host, and any single-process run are blind to host-role bugs. +4. **That event's resulting state is recorded on both peers and confirmed to match**: + object counts and any mutated shared world state, read on each instance with + `netcode.ghost get` (Unity Netcode) or `script eval` (NGO `NetworkVariable` + values), not "it looked right". This is + unhappy-path test 8 in [netcode-lifecycle.md](netcode-lifecycle.md), promoted into + the gate because it catches host-role divergence empirically. +5. If the project predicts anything, prediction is verified **in two processes** per + *Verifying prediction* in [performance-and-scale.md](performance-and-scale.md), with + `netcode.profiler get_rollback_metrics` from a client instance as evidence. A + single-world host is never replayed, so single-process tests only take the + authority path. +6. If player-build verification is claimed, the EditorBuildSettings scene list is + non-empty and the build verifiably postdates the last source change (see *Proving a + build is current* in [netcode-lifecycle.md](netcode-lifecycle.md)). +7. Parity is accounted for: every gameplay feature the single-process build has is either + exercised across processes in the cited evidence or named in the decision record as a + deferral with its reason. A feature disabled only for networked play without such an + entry is a defect. + +A regression test is not one until it has been observed to fail with the fix removed. +For host-role and prediction bugs, see the note under unhappy-path test 8 in +[netcode-lifecycle.md](netcode-lifecycle.md). + +For a ghost or NGO implementation, zero hits for the chosen stack's types, or missing +runtime evidence, is a failed completion check: record it in the decision record as a +gap, not as done. Session-only work fails only when its session create, join or read-back +evidence is missing. diff --git a/skills/setup-multiplayer-services/references/workflows-prerequisites.md b/skills/build-multiplayer-game/references/workflows-prerequisites.md similarity index 71% rename from skills/setup-multiplayer-services/references/workflows-prerequisites.md rename to skills/build-multiplayer-game/references/workflows-prerequisites.md index dfc00d5..7ce5280 100644 --- a/skills/setup-multiplayer-services/references/workflows-prerequisites.md +++ b/skills/build-multiplayer-game/references/workflows-prerequisites.md @@ -1,6 +1,6 @@ -## Workflow prerequisites (packages and cloud setup) +# Workflow prerequisites (packages and cloud setup) -Relative links in this file resolve to the skill directory's `references/` folder. +Links in this file resolve to the skill directory's `references/` folder, the folder this file is in. Project and package paths in code spans are relative to the user's project or the package root. **Agent-only sanity check** before recommending a path: match the user's **intent** to **dependencies** and **live services / deployment** (see **`llms.txt`** install, init, deployment, and tutorial pages for authoritative steps). Package IDs can vary slightly by Unity/editor version—verify in Package Manager or docs when implementing. @@ -8,10 +8,12 @@ Relative links in this file resolve to the skill directory's `references/` folde Unity Gaming Services **initialization** and **authentication** are required for all workflows. +Check current service availability and pricing for the chosen hosting and matchmaking setup before committing to it. + | Workflow (what the product is doing) | Typically required | |--------------------------------------|-------------------| | Rooms / join-in-progress **without** starting the session **gameplay network** (metadata, codes, lists, properties only) | `com.unity.services.multiplayer`. **No** Netcode gameplay package required unless they add a custom **`INetworkHandler`** or later start **`StartRelayNetworkAsync`** / **`StartDirectNetworkAsync`**. | -| **Gameplay** simulation synced over the session **Network** (host/client or server roles with Relay or direct transport) | **Exactly one** gameplay stack: **NGO** — `com.unity.netcode.gameobjects` **or** **NFE** — `com.unity.netcode.entities` (Netcode for Entities). Integrate transport with session network APIs per Unity's session + Netcode guides; do not assume both stacks. | +| **Gameplay** simulation synced over the session **Network** (host/client or server roles with Relay or direct transport) | **One** gameplay stack, chosen per [choosing-netcode.md](choosing-netcode.md): NGO (`com.unity.netcode.gameobjects`) for games with no prediction, rollback or lag-compensation need, or `com.unity.netcode` (GhostObject/GhostBehaviour when the installed package has a public `GhostObject` type, otherwise direct ECS ghosts) for games that need them. NGO 3.x itself installs `com.unity.netcode` and the Entities packages, so read its `package.json` for the minimum Editor and keep NGO 2.x on older Editors; it also needs Burst-capable targets. An existing project keeps its stack. Never let two stacks write the same state. Integrate transport with session network APIs per Unity's session + Netcode guides. | | **Quick join** (filter-based auto pick / create) | Session **type** and **indexed** properties for filters; **`QuickJoinOptions`** in code. | | **Ticket matchmaking** into a **player-hosted** match | A deployed **Matchmaker queue (MMQ)** (name matches **`MatchmakerOptions`**), Matchmaker **environment** / dashboard setup, and authenticated players. | | **Ticket matchmaking** with a **dedicated game server (DGS)** | **MMQ** configured for the **DGS / server allocation** flow, a **server build** and **hosting** setup (e.g. Game Server Hosting / Multiplay—see **`llms.txt`** hosting and deployment topics), server process using the **server** session role where applicable, and often **`WithBackfillingConfiguration`** + **`StartBackfillingAsync`** / **`StopBackfillingAsync`** when refilling player slots on an existing allocation. | diff --git a/skills/setup-multiplayer-services/SECURITY.md b/skills/setup-multiplayer-services/SECURITY.md deleted file mode 100644 index 58a6487..0000000 --- a/skills/setup-multiplayer-services/SECURITY.md +++ /dev/null @@ -1,17 +0,0 @@ -# Security notes: setup-multiplayer-services - -This skill has the agent read state from the user's open Unity Editor through `unity command script eval` to read the Cloud project ID after linking and the session result of a feature it changed. Automated skill scanners flag that as a powerful capability. It is intentional, and it is limited by the safeguards below. - -## Accepted risks - -| Risk | Capability | Why it is accepted | -|---|---|---| -| `SEC_POWER_CAP` | Runs C# in the user's open Editor through `unity command script eval` | It only reaches the Editor the user already has open, on their own machine, as that user, so it grants nothing they couldn't do themselves. `script eval` sits behind the Pipeline capability gate. No code fetched from a remote source is run. The skill uses it only to read state, and uses `unity command console status` for the console check. | - -## Mitigations - -- **Only the user's own Editor.** `unity command script eval` talks to the Editor open on this machine. It can't reach another machine or another user's Editor. -- **Capability gate.** `script eval` is only available when the project's Pipeline package provides it. -- **No remote code.** The agent runs C# it writes itself to read Editor state. Nothing downloaded from outside is executed. -- **Read only, once.** The skill enters Play mode at most once per change and reads state instead of adding logging. Any temporary verification code is removed afterwards. -- **One Editor.** Every `unity command` names the project with `--project-path`, so it can't drive another project's Editor. diff --git a/skills/setup-multiplayer-services/SKILL.md b/skills/setup-multiplayer-services/SKILL.md deleted file mode 100644 index c258fc2..0000000 --- a/skills/setup-multiplayer-services/SKILL.md +++ /dev/null @@ -1,84 +0,0 @@ ---- -name: setup-multiplayer-services -description: Guides real-time online multiplayer with Unity Multiplayer Services. Use when the user asks about network topology, hosting, matchmaking, or session-based play such as rooms, parties, and lobbies, not backend features. ---- - -# Multiplayer SDK (Unity Multiplayer Services) - -## Before you start - -1. If the task changes the project (code, packages, settings or the Unity Cloud link), create a restore point you can roll back to if your changes fail: commit the project in version control, or copy the project folder if there is none. An advice-only request changes nothing, so it needs no restore point. -2. Before you go forward with a workflow or diagnosis, open and read the documentation pages for it from the [Documentation pages](#documentation-pages) list, and name the pages you read in your response. This is because your training knowledge about Unity Multiplayer Services might be out of date, incorrect, or for the wrong package version. -3. Do only what's asked. Don't change unrelated assets or files. Avoid long explanations. -4. Never leave verification code in the user's script. Never build logging or detection they didn't ask for. - -## Documentation pages - -Prefer fetching the page directly (for example `WebFetch`) over searching (for example `WebSearch`): it is faster and lands on the exact reference. Only fetch what you need. Pages on docs.unity.com are unversioned and available as Markdown when the URL ends in `.md`, so there is no `` to replace. For the installed package version, read `Packages/packages-lock.json`. - -- [Get started](https://docs.unity.com/en-us/mps-sdk/get-started.md): ways to add session-based multiplayer. -- [Install the SDK](https://docs.unity.com/en-us/mps-sdk/install-and-upgrade.md): the Multiplayer Services package and migration from the standalone SDKs. -- [Initialize UGS and authenticate the player](https://docs.unity.com/en-us/mps-sdk/init-ugs.md): the init and sign-in that every session call needs. -- [Create a session](https://docs.unity.com/en-us/mps-sdk/create-session.md): session options and network connection types. -- [Find and join a session](https://docs.unity.com/en-us/mps-sdk/join-session.md): join code, browsing, reconnecting. -- [Matchmaking](https://docs.unity.com/en-us/mps-sdk/matchmake-session.md): matchmade sessions; [Quick Join](https://docs.unity.com/en-us/mps-sdk/matchmake-lobby.md) for the fast path. -- [Session configuration options](https://docs.unity.com/en-us/mps-sdk/config-options.md): options and their defaults. -- [Connect players through a relay](https://docs.unity.com/en-us/mps-sdk/connect-players.md): host-based play without dedicated servers. -- [Session error messages](https://docs.unity.com/en-us/mps-sdk/lobby-error-messages.md): error codes for troubleshooting. -- [Full documentation map](https://docs.unity.com/en-us/mps-sdk/llms.txt): every other page. - -## Instructions - -1. **Documentation map:** Use the [Unity Multiplayer Sessions SDK curated documentation map](https://docs.unity.com/en-us/mps-sdk/llms.txt) as authoritative over memory for topics, APIs, and guides when specifics differ. Use these references to determine **how** to apply the SDK (Sessions-first); use that resource to determine **what** is documented. **Never** mention the `llms.txt` filename to the user. If that map is unreachable (network, tooling), treat this skill's markdown references plus the installed package's docs as the source of truth for specifics: read only the `.md` files in `/Library/PackageCache/com.unity.services.multiplayer@*/`. - -2. **Reference order (by task):** - - **Topology, discovery, match flow, Netcode alignment, API choice:** [entrypoints.md](references/entrypoints.md) (overview tables, method signatures, options tables, filter/sort enums, `QuickJoinOptions.Timeout`, errors) → [implementation-fit.md](references/implementation-fit.md) → [examples.md](references/examples.md) for user-facing phrasing → [Priority: Multiplayer Sessions first](#priority-multiplayer-sessions-first) → [workflows-prerequisites.md](references/workflows-prerequisites.md) for extra depth. - - **Dedicated game server (`Unity.Services.Multiplayer.Server`):** [dgs-entrypoint.md](references/dgs-entrypoint.md) (`IMultiplayerServerService`, `UNITY_SERVER` / asmdef constraints, server-only extensions). - - **Lower-level service clients:** [underlying-services.md](references/underlying-services.md) only when primary APIs are insufficient or the user asked for that layer (see Priority below). - -3. **Cloud link:** session, Relay and matchmaking calls need the project linked to a Unity Cloud project (project ID). Linking writes `ProjectSettings/ProjectSettings.asset`, so link only when the task needs those calls or the user asked to link, and only after the restore point from [Before you start](#before-you-start). For an advice-only request, such as a hosting recommendation, don't link: say the project needs linking and give the `unity projects link cloud` command. - 1. Check the link: a non-empty `cloudProjectId` in `ProjectSettings/ProjectSettings.asset` means the project is linked. If it is, skip the rest. - 2. Choose the backend before you link. Without `--cloud-project`, `unity projects link cloud` reuses `UNITY_CLOUD_PROJECT`, then the organization's saved default project, and creates a new cloud project only when neither is set. Run `unity cloud project current --format json` and read `defaultCloudProjectId`. To reuse a backend, ask the user which one if it is not clear and pass its ID with `--cloud-project `. To create a new one, `UNITY_CLOUD_PROJECT` must be unset and `defaultCloudProjectId` null; if either is set, ask the user whether to reuse that project. To create one instead, clear the default with `unity cloud project clear-default`, and have the user unset `UNITY_CLOUD_PROJECT` in their own shell, because `clear-default` does not touch the variable. - 3. Check `Packages/manifest.json` for `com.unity.pipeline`, because a graceful `unity close`, `--until-ready` and `script eval` need it. If it is missing, add it with `unity pipeline install --project-path ` (Unity 6.0+) and say so in the report. If it can't be added, ask the user to save and close the Editor themselves, and in the verify step check only the asset. - 4. `unity close ` exits without saving, so ask the user to save their work, then close the Editor with it, because an open Editor keeps the old link and its next settings save can erase the new one. - 5. Run `unity projects link cloud --format json`, adding `--cloud-project ` only when reusing a backend. When it will create a project, first ask whether the game is directed at children under 13 and add `--coppa compliant` if so: the default is `not_compliant`. Never pass `--coppa` with `--cloud-project` (error `COPPA_ARGS_CONFLICT`); change an existing project's COPPA setting in the Unity Cloud dashboard. - 6. Verify. If `data.editor.restartRequired` is `true`, an Editor still had the project open: close it, then check the asset still holds the new ID, and if not run the link again with `--cloud-project `. Reopen the project with `unity open --until-ready --format json` (a plain `unity open` returns before the Editor can answer commands), then confirm `cloudProjectId` in `ProjectSettings/ProjectSettings.asset` and `CloudProjectSettings.projectId` in the Editor (read with `unity command script eval --project-path `) both equal `data.cloudProject`'s ID. If they don't, or the command fails, stop and report the error code to the user. - 7. Don't hand-edit `ProjectSettings/ProjectSettings.asset` or write an Editor-side linker script, because the CLI sets the project ID and organization consistently and a manual edit can leave them mismatched. If a flag or output field differs from this step, run `unity projects link cloud --help`. - -## Priority: Multiplayer Sessions first - -When the task is **choosing** topology, discovery, match flow, or Netcode alignment—not only calling APIs—ground recommendations via [implementation-fit.md](references/implementation-fit.md) (conversation → project → short targeted questions). - -**Primary path:** Implement against **`Unity.Services.Multiplayer`** using **`IMultiplayerService` / `MultiplayerService.Instance`** and **`ISession`** (surface summary in [entrypoints.md](references/entrypoints.md)); keep composed flows consistent with `llms.txt`. - -**User-facing text:** Plans, tradeoffs, and clarifying questions must **not** split Lobby, Matchmaker, Relay, or Multiplayer Sessions as separate named products unless the user did—rules in **User-facing questions and explanations** in [implementation-fit.md](references/implementation-fit.md), samples in [examples.md](references/examples.md). Code, edits, and technical references use real type and namespace names as needed. - -**Underlying clients** (`Unity.Services.Lobbies`, `Unity.Services.Matchmaker`, `Unity.Services.Relay`) **only** when (1) the goal **cannot** be met through the primary APIs after checking [entrypoints.md](references/entrypoints.md), or (2) the user **explicitly** asked for those namespaces or products. Do **not** default implementations there. - -## Final step - -If you changed the project, run these checks. If one fails, reread the matching pages from [Documentation pages](#documentation-pages) and the reference files, fix the cause, and run the checks again. - -1. Check the project has zero console errors with `unity command console status`. Pass `--project-path ` to every `unity command` here, because without it the CLI drives the Editor of the shell's current folder, which may be another project. Older Editors expose it as `console_status`: confirm which with `unity commands --grep console`. -2. Stop after step 1 unless the user asked for proof or you suspect a specific fault, and report that the feature was not run. To chase that fault, enter Play mode once (`unity command editor.playmode start`), create a session the way the user's code does, read the session ID and player count through `unity command script eval` rather than adding logging, then repeat step 1. Remove any temporary code afterwards. Take no screenshots. A missing project ID error means the cloud link in [Instructions](#instructions) step 3 did not take. - -## Final report - -End your response with a short report: - -1. What you changed: files, packages, and the Unity Cloud project you linked (its ID, and whether the link created it). -2. The checks from [Final step](#final-step) you ran and their results, including any you could not run and why. -3. Side effects, such as an Editor you closed and reopened. -4. Follow-ups only the user can do, such as enabling a service in the Unity Dashboard or restoring from the restore point if they reject the changes. -5. Which documentation pages you read. - -## Additional resources - -Read from this entrypoint only; links are one level under this skill folder (no `references/index.md` or README hub). - -- **[implementation-fit.md](references/implementation-fit.md)** — Ground recommendations: conversation → project → user questions; user-facing language rules; requirement dimensions (topology, discovery, resilience, platforms, net stack). -- **[examples.md](references/examples.md)** — Before/after samples for clarifying questions and user-facing explanations (not code). -- **[entrypoints.md](references/entrypoints.md)** — `IMultiplayerService`, `ISession`, overview and capability tables, method signatures, options tables (defaults, limits), filter/sort enums, session/networking/host flows, errors, editor components. -- **[dgs-entrypoint.md](references/dgs-entrypoint.md)** — Dedicated server: `Unity.Services.Multiplayer.Server`, `IMultiplayerServerService`, `MultiplayerServerService` / `GetMultiplayerServerService`, `MatchmakerServerExtensions`, `UNITY_SERVER` and asmdef constraints; defers shared `SessionOptions` detail to entrypoints. -- **[workflows-prerequisites.md](references/workflows-prerequisites.md)** — Package and cloud prerequisites by workflow (tables). -- **[underlying-services.md](references/underlying-services.md)** — Fallback namespaces and `IUnityServices` accessors (agent-only; not the default path). diff --git a/skills/setup-multiplayer-services/references/entrypoints.md b/skills/setup-multiplayer-services/references/entrypoints.md deleted file mode 100644 index ef73f2e..0000000 --- a/skills/setup-multiplayer-services/references/entrypoints.md +++ /dev/null @@ -1,213 +0,0 @@ -## Table of Contents - -- [Overview](#overview) -- [IMultiplayerService capabilities](#imultiplayerservice-capabilities) -- [Method signatures](#method-signatures) -- [Options reference](#options-reference) -- [Session configuration](#session-configuration-sessionoptions-joinsessionoptions-basesessionoptions) -- [Netcode with session options](#netcode-with-withnetwork-session-options) -- [Networking model](#networking-model-session-side) -- [Host / server session](#host--server-session-ihostsession-iserversession) -- [Matchmaking results](#matchmaking-results-on-a-session) -- [Errors and observation](#errors-and-observation) -- [Editor / glue](#editor--glue-unityservicesmultiplayercomponents) - -## Overview - -| Topic | Details | -|--------|---------| -| **Service access** | `MultiplayerService.Instance` (static) or `unityServices.GetMultiplayerService()` via `UnityServicesExtensions` after Services initialization. | -| **Core type** | **`ISession`** — session state, players, properties, role (host/member/server), **`Network`** (client), **`LeaveAsync`**, **`ReconnectAsync`**, **`RefreshAsync`**, **`SaveCurrentPlayerDataAsync`**; cast to **`IHostSession`** / **`IServerSession`** when hosting or dedicated server. | - -### `IMultiplayerService` capabilities - -| Area | What to use | -|------|-------------| -| **Session registry** | `Sessions` (read-only map); events `SessionAdded`, `SessionRemoved`, `AddingSessionStarted`, `AddingSessionFailed`. | -| **Create / join** | `CreateSessionAsync`, `CreateOrJoinSessionAsync`, `JoinSessionByIdAsync`, `JoinSessionByCodeAsync`, `ReconnectToSessionAsync`, `GetJoinedSessionIdsAsync`. | -| **Matchmaking into a session** | `MatchmakeSessionAsync` with **`QuickJoinOptions`** (filters, timeout, optional create) or **`MatchmakerOptions`** (queue, ticket attributes, player properties) + **`SessionOptions`**; optional `CancellationToken` on the `MatchmakerOptions` overload. | -| **Discovery** | `QuerySessionsAsync` + **`QuerySessionsOptions`** (filters, sort, skip/count, continuation token); **`QuerySessionsResults`** may **`StartPolling`** / **`StopPolling`**. | - -### Method signatures - -```csharp -// Creates a new session. Returns IHostSession (host-side). Throws SessionException on failure. -Task CreateSessionAsync(SessionOptions sessionOptions) - -// Joins session by ID, or creates it if it does not exist. -Task CreateOrJoinSessionAsync(string sessionId, SessionOptions sessionOptions) - -// Joins an existing session by its ID. -Task JoinSessionByIdAsync(string sessionId, JoinSessionOptions sessionOptions = default) - -// Joins an existing session via a human-readable join code. -Task JoinSessionByCodeAsync(string sessionCode, JoinSessionOptions sessionOptions = default) - -// Reconnects to a previously joined session after a disconnect. -Task ReconnectToSessionAsync(string sessionId, ReconnectSessionOptions options = default) - -// Finds and joins a session using Unity's matchmaker service. Supports cancellation. -Task MatchmakeSessionAsync(MatchmakerOptions matchOptions, SessionOptions sessionOptions, CancellationToken cancellationToken = default) - -// Finds a session using session filters with retries up to a timeout. Can optionally create a session if none is found. -Task MatchmakeSessionAsync(QuickJoinOptions quickJoinOptions, SessionOptions sessionOptions) - -// Browses available sessions matching the provided query options. -Task QuerySessionsAsync(QuerySessionsOptions queryOptions) - -// Returns IDs of all sessions the current player is already part of. -Task> GetJoinedSessionIdsAsync() -``` - -### Options reference - -#### `SessionOptions` _(create / create-or-join / matchmake)_ - -Inherits `BaseSessionOptions`. - -| Property | Type | Default | Description | -|---|---|---|---| -| `Name` | `string` | new GUID | Session display name | -| `MaxPlayers` | `int` | `0` | Max players including host. Must be > 0 when creating | -| `IsLocked` | `bool` | `false` | Locked sessions reject new joins | -| `IsPrivate` | `bool` | `false` | Private sessions are hidden from queries and quick-join | -| `Password` | `string` | `null` | 8–64 char password required to join. Not readable back from the session | -| `SessionProperties` | `Dictionary` | empty | Custom game-specific session properties (e.g. `"map"`). Up to 20 total | -| `Type` | `string` _(from base)_ | new GUID | Client-side key identifying the session type | -| `PlayerProperties` | `Dictionary` _(from base)_ | empty | Per-player properties (e.g. `"role"`). Up to 10 per player | - -Fluent extensions (on `SessionOptionsExtensions`): `.WithRelayNetwork()`, `.WithDirectNetwork()`, `.WithDistributedAuthorityNetwork()`, `.WithNetworkHandler()`, `.WithHostMigration()`, `.WithPlayerName()` - ---- - -#### `JoinSessionOptions` _(join by ID / join by code / quick-join fallback)_ - -Inherits `BaseSessionOptions`. - -| Property | Type | Default | Description | -|---|---|---|---| -| `Password` | `string` | `null` | Password required if the session is password-protected | -| `Type` | `string` _(from base)_ | new GUID | Client-side session type key | -| `PlayerProperties` | `Dictionary` _(from base)_ | empty | Per-player properties | - ---- - -#### `ReconnectSessionOptions` _(reconnect)_ - -| Property | Type | Default | Description | -|---|---|---|---| -| `Type` | `string` | new GUID | Client-side session type key | - -Fluent: `.WithNetworkHandler(INetworkHandler)` — disables default NGO/NfE integration. - ---- - -#### `MatchmakerOptions` _(matchmake via Unity Matchmaker)_ - -| Property | Type | Default | Description | -|---|---|---|---| -| `QueueName` | `string` | `null` | Name of the Matchmaker queue | -| `TicketAttributes` | `Dictionary` | empty | Attributes sent with the matchmaking ticket | -| `PlayerProperties` | `Dictionary` | empty | Per-player properties forwarded to matchmaker | - ---- - -#### `QuickJoinOptions` _(matchmake via filters)_ - -| Property | Type | Default | Description | -|---|---|---|---| -| `Filters` | `List` | empty | Filters a session must satisfy to be joined | -| `Timeout` | `TimeSpan` | default | How long to retry before giving up and optionally creating a new session | -| `CreateSession` | `bool` | `false` | Create a new session if none is found within the timeout | - -> Do not set `Timeout` unless explicitly requested. - ---- - -#### `QuerySessionsOptions` _(query)_ - -| Property | Type | Default | Description | -|---|---|---|---| -| `Count` | `int` | `100` | Max results to return | -| `Skip` | `int` | `0` | Pagination offset | -| `FilterOptions` | `List` | empty | Filters to narrow results | -| `SortOptions` | `List` | empty | Sort order for results | -| `ContinuationToken` | `string` | `null` | Token for fetching the next page | - ---- - -#### `FilterOption` _(used in `QuickJoinOptions` and `QuerySessionsOptions`)_ - -Constructor: `FilterOption(FilterField field, string value, FilterOperation operation)` - -| Enum | Values | -|------|--------| -| **`FilterField`** | `MaxPlayers`, `AvailableSlots`, `Name`, `Created` (RFC3339), `LastUpdated` (RFC3339), `IsLocked`, `HasPassword`, `StringIndex1–5`, `NumberIndex1–5` | -| **`FilterOperation`** | `Contains` _(Name only)_, `Equal`, `NotEqual`, `Less`, `LessOrEqual`, `Greater`, `GreaterOrEqual` | - ---- - -#### `SortOption` _(used in `QuerySessionsOptions`)_ - -Constructor: `SortOption(SortOrder order, SortField field)` - -| Enum | Values | -|------|--------| -| **`SortOrder`** | `Ascending`, `Descending` | -| **`SortField`** | `Name`, `MaxPlayers`, `AvailableSlots`, `CreationTime`, `LastUpdated`, `Id`, `StringIndex1–5`, `NumberIndex1–5` | - ---- - -#### `AddingSessionOptions` _(event payload — read-only)_ - -| Property | Type | Description | -|---|---|---| -| `Type` | `string` | The session type passed to the create/join call | - ---- - -### Session configuration (`SessionOptions`, `JoinSessionOptions`, `BaseSessionOptions`) - -| Topic | Details | -|--------|---------| -| **Lobby-like fields** | Max players, name, password, locked/private flags, typed **`Type`**, **session** and **player** properties with **`VisibilityPropertyOptions`** (Public / Member / Private) and indexed slots (**`PropertyIndex`**) for query filters. | -| **Networking** (`SessionOptionsExtensions`) | **`WithRelayNetwork`**, **`WithDirectNetwork`** (listen/publish IP/port or **`DirectNetworkOptions`**), **`WithNetworkOptions`** (e.g. **`RelayProtocol`**), **`WithNetworkHandler`** for custom **`INetworkHandler`**. | -| **Host migration** | **`WithHostMigration`** + **`IMigrationDataHandler`**; on **`IHostSession`**: **`GetHostMigrationDataAsync`** / **`SetHostMigrationDataAsync`**. | -| **Player name** | **`WithPlayerName`** (visibility). | -| **Matchmaker backfill** | **`MatchmakerServerExtensions.WithBackfillingConfiguration`** on **`SessionOptions`**; on matchmade **`ISession`**: **`StartBackfillingAsync`** / **`StopBackfillingAsync`**. See **`llms.txt`** and package docs for hosting constraints. | - -### Netcode with `With*Network*` session options - -| Condition | Behavior | -|-----------|----------| -| **`SessionOptionsExtensions`** include gameplay networking (**`WithRelayNetwork`**, **`WithDirectNetwork`**, **`WithNetworkOptions`**, **`WithNetworkHandler`**, …) | **create / join / matchmake / reconnect** bring up **NGO** or **NFE** as configured—no separate Netcode start for that path. | - -### Networking model (session side) - -| Surface | Role | -|---------|------| -| **`IHostSessionNetwork`** | **`StartDirectNetworkAsync`**, **`StartRelayNetworkAsync`**, **`StopNetworkAsync`**; state and failure events; **`INetworkHandler`**. | -| **`IClientSessionNetwork`** | Client **`NetworkState`** and events; **`NetworkHandler`**. | -| **`NetworkConfiguration`** | UTP endpoints and Relay server data; **`NetworkType`**: Direct, Relay, **DistributedAuthority**; **`NetworkRole`**: Client, Server, Host. | - -### Matchmaking results on a session - -| API | Use when | -|-----|----------| -| **`MatchmakerExtensions.GetMatchmakingResults(ISession)`** | Stored matchmaking results are needed after a matchmade session exists. | - -### Errors and observation - -All async methods on **`IMultiplayerService`** throw **`SessionException`** on failure; **`SessionException`** exposes a specific session error type and message. - -| Type | Role | -|------|------| -| **`SessionException`** / **`SessionError`** | Session and composed flows. | -| **`SessionObserver`** | Watch add/fail events for a given session **type**. | - -### Editor / glue (`Unity.Services.Multiplayer.Components`) - -| Item | Role | -|------|------| -| **`MultiplayerSession`** (ScriptableObject) | Holds **`ISession`** and UnityEvent groups (lifecycle, session, players). | -| **`SessionConnector`** / **`SessionConnectorBehaviour`** | Create or create-or-join flows (e.g. on sign-in). | diff --git a/skills/setup-multiplayer-services/references/implementation-fit.md b/skills/setup-multiplayer-services/references/implementation-fit.md deleted file mode 100644 index aad1d8c..0000000 --- a/skills/setup-multiplayer-services/references/implementation-fit.md +++ /dev/null @@ -1,32 +0,0 @@ -## Implementation fit: clarify multiplayer requirements - -Relative links in this file resolve to the skill directory's `references/` folder. - -Before recommending architecture or APIs internally, the agent **must** ground advice in the right product choices for *this* application. Map answers to [entrypoints.md](entrypoints.md) and this skill's **Priority: Multiplayer Sessions first** section only **after** requirements are clear (from context, project, or user). For concrete phrasing samples, see [examples.md](examples.md). - -**How to obtain requirements (in order):** - -1. **Conversation and task context** — Use stated goals (e.g. "2-player co-op", "ranked 5v5", "mobile", "host leaves often"). -2. **Project state when available** — Inspect the workspace (e.g. `Packages/manifest.json` for Netcode / multiplayer packages, existing multiplayer or networking scripts, platform settings) and align recommendations with what is already chosen. -3. **Ask the user** — If a dimension below would **change** the recommended approach and is not inferable from (1) or (2), ask a **short, targeted** question instead of assuming. Follow **User-facing questions and explanations** below. - -### User-facing questions and explanations - -- **Clarifying questions** must stay **high level**: player count, how people **find or join** a game, who **runs** the match (e.g. one player's machine vs a dedicated machine), fairness/latency expectations, disconnect/reconnect and "host leaves" behavior, target platforms, and which **Unity networking stack** the project already uses **only if** the user has brought it up or it is visible in the project. Phrase questions in **game / product** terms. -- **Do not** name or ask about Unity **product or service** implementations in questions: e.g. avoid the terms **Sessions**, **Lobby**, **Matchmaker**, **Relay**, and avoid prompting with **API or type names** (`ISession`, `QuerySessionsAsync`, etc.). The user should not need SDK vocabulary to answer. -- In **explanations, summaries, and plans** addressed to the user (outside of code blocks and file edits), **do not mention** Lobby, Matchmaker, Relay, or Multiplayer **Sessions** as named products, and **do not** contrast or enumerate those **underlying services**—unless the **user explicitly** asked about them by name or asked for that level of SDK/architecture detail. Use plain language (e.g. "list of open games", "automatic pairing", "brokered connectivity when direct player-to-player links are unreliable", "the main Unity multiplayer package API") when a concept must be described. -- **Code, API references, and file contents** may use the exact types, namespaces, and methods from this skill and from `llms.txt` as needed for a correct implementation. - -### Dimensions to consider - -- **Player count and topology** — Players per match and rough scale (many small matches vs few large ones). Whether the simulation can run on a **host client** (often with mediated connectivity) or needs a **dedicated server** / server-authoritative hosting story. *Internal mapping:* relay vs direct listen/publish, host vs dedicated server roles, capacity limits on the multiplayer entrypoint APIs. - -- **Casual vs competitive** — Tolerance for **host-based authority** and latency variance vs need for **stricter authority, consistency, and fairness** (often favoring dedicated servers and careful netcode choices). Informs how strongly to push dedicated hosting, tick/interpolation choices, and cheat-sensitive design (without duplicating full anti-cheat guidance here). - -- **Discovery and how matches form** — Join codes or invites vs **browsing a list** of open games vs **automatic pairing**; visibility and filterable game metadata. *Internal mapping:* query/list flows, quick-join-style filters, ticket/queue flows; session properties and indexes as needed. - -- **Connection model and resilience** — **NAT / home networks** (need for mediated connectivity vs published listen addresses), **reconnect** after disconnects, and **moving the host** without ending the match. *Internal mapping:* relay vs direct network options, `ReconnectAsync`, host migration hooks, network start/stop. - -- **Platform constraints** — Targets (e.g. **mobile** dropouts and backgrounding, **console** networking and certification expectations) that affect match lifetime, reconnect UX, and viable connection patterns. - -- **Team skills and codebase stack** — **Netcode for GameObjects** vs **Netcode for Entities** (or other networking) must match packages and patterns already in the project; prefer extending the stack in `manifest.json` and existing code rather than introducing a parallel net model without an explicit user request.