unity-networking
Unity multiplayer networking with NGO, Mirror, Photon, and Fish-Net. PROACTIVELY activate for: (1) building Unity multiplayer games, (2) Netcode for GameObjects (NGO) setup and patterns, (3) Mirror networking, (4) Photon PUN and Photon Fusion, (5) Fish-Net networking, (6) RPCs (ClientRpc, ServerRpc), (7) NetworkVariable and network synchronization, (8) lobby and matchmaking systems, (9) dedicated server hosting and Relay, (10) server-authoritative architecture, (11) lag compensation and prediction. Provides: networking-stack comparison, NGO templates, RPC patterns, NetworkVariable usage, lobby/matchmaking setup, and authoritative-server design.
What this skill does
# Unity Networking and Multiplayer
## Overview
Reference for implementing multiplayer systems and backend services in Unity. Covers the major networking frameworks, authority models, common multiplayer patterns, and Unity Gaming Services integration.
## Networking Framework Comparison
| Framework | Type | Best For | License |
|-----------|------|----------|---------|
| Netcode for GameObjects (NGO) | Client-hosted / Dedicated | Unity-native projects, UGS integration | Free (Unity) |
| Mirror | Client-hosted / Dedicated | Open-source alternative, mature ecosystem | MIT |
| Photon PUN 2 | Cloud-hosted | Quick prototyping, room-based games | Free tier + paid |
| Photon Fusion 2 | Cloud/Self-hosted | Competitive games, tick-based simulation | Free tier + paid |
| Fish-Net | Client-hosted / Dedicated | Performance-critical, Mirror alternative | MIT |
## Netcode for GameObjects (NGO)
### Setup
1. Install via Package Manager: `com.unity.netcode.gameobjects`
2. Add `NetworkManager` to a scene GameObject
3. Select transport (Unity Transport is default)
4. Mark networked prefabs with `NetworkObject` component
5. Register prefabs in NetworkManager's prefab list
### Core Components
| Component | Purpose |
|-----------|---------|
| `NetworkManager` | Manages connections, spawning, scene management |
| `NetworkObject` | Required on all networked GameObjects |
| `NetworkBehaviour` | Base class for networked scripts (replaces MonoBehaviour) |
| `NetworkVariable<T>` | Synchronized variable with ownership/permissions |
| `NetworkTransform` | Automatic position/rotation sync |
| `NetworkAnimator` | Automatic Animator parameter sync |
### RPCs (Remote Procedure Calls)
```csharp
public class PlayerCombat : NetworkBehaviour
{
NetworkVariable<int> _health = new(100,
NetworkVariableReadPermission.Everyone,
NetworkVariableWritePermission.Server);
[ServerRpc]
void AttackServerRpc(ulong targetId)
{
// Runs on server - validate and apply damage
if (!IsServer) return;
var target = NetworkManager.SpawnManager.SpawnedObjects[targetId];
target.GetComponent<PlayerCombat>().TakeDamage(10);
}
[ClientRpc]
void PlayHitEffectClientRpc(Vector3 position)
{
// Runs on all clients - visual feedback only
Instantiate(hitVFX, position, Quaternion.identity);
}
void TakeDamage(int amount)
{
_health.Value -= amount;
PlayHitEffectClientRpc(transform.position);
}
}
```
| RPC Type | Direction | Use For |
|----------|-----------|---------|
| `[ServerRpc]` | Client -> Server | Player actions, requests |
| `[ClientRpc]` | Server -> All Clients | VFX, sound, UI updates |
| `[ClientRpc(SendTo.Owner)]` | Server -> Owner Client | Owner-specific feedback |
### NetworkVariable Permissions
```csharp
// Server-writable (default) - authoritative state
NetworkVariable<int> score = new(0, writePerm: NetworkVariableWritePermission.Server);
// Owner-writable - client-authoritative (use sparingly)
NetworkVariable<Vector3> cursorPos = new(writePerm: NetworkVariableWritePermission.Owner);
```
Use `OnValueChanged` callback for UI reactions:
```csharp
_health.OnValueChanged += (oldVal, newVal) => healthBar.value = newVal;
```
## Authority Models
| Model | Description | When to Use |
|-------|-------------|-------------|
| Server-Authoritative | Server validates all actions, clients are thin | Competitive, anti-cheat critical |
| Client-Authoritative | Clients own their state, server relays | Cooperative, trust-based |
| Client Prediction + Server Reconciliation | Client predicts locally, server corrects | FPS, fast-paced action |
| Relay / Listen Server | One player hosts, others connect via relay | Casual, small lobbies |
### Server-Authoritative Flow
```text
Client: Press "Attack" -> Send ServerRpc(targetId)
Server: Validate range/cooldown -> Apply damage -> Update NetworkVariable
Server: Send ClientRpc for VFX
All Clients: Play hit effect
```
Never trust client data. Validate positions, cooldowns, ammunition, and line-of-sight on the server.
## Common Multiplayer Patterns
### Lobby System
```text
1. Player authenticates (UGS Auth / custom)
2. Player creates or joins lobby (UGS Lobby / custom)
3. Lobby fills -> host starts game
4. Relay allocation for NAT traversal (UGS Relay)
5. All players connect to relay
6. NetworkManager starts host/client
```
### Spawn and Despawn
```csharp
// Server-side spawning
var instance = Instantiate(prefab, spawnPoint, Quaternion.identity);
instance.GetComponent<NetworkObject>().SpawnWithOwnership(clientId);
// Server-side despawning
networkObject.Despawn(); // Removes from all clients
```
### Scene Management
Use `NetworkManager.SceneManager.LoadScene("GameScene", LoadSceneMode.Single)` for synchronized scene loading. Only the server/host should call this.
## REST API and WebSocket Integration
### REST API (UnityWebRequest)
```csharp
async Awaitable<T> GetAsync<T>(string url)
{
using var request = UnityWebRequest.Get(url);
request.SetRequestHeader("Authorization", $"Bearer {token}");
await request.SendWebRequest();
if (request.result != UnityWebRequest.Result.Success)
throw new Exception(request.error);
return JsonUtility.FromJson<T>(request.downloadHandler.text);
}
```
Use `JsonUtility` for simple types or Newtonsoft.Json (`com.unity.nuget.newtonsoft-json`) for complex serialization. Always use `using` with UnityWebRequest to prevent memory leaks.
### WebSocket (NativeWebSocket / WebSocketSharp)
For real-time non-game communication (chat, notifications), use a WebSocket library. NativeWebSocket works across platforms including WebGL.
## Unity Gaming Services (UGS)
| Service | Package | Purpose |
|---------|---------|---------|
| Authentication | `com.unity.services.authentication` | Anonymous/platform sign-in |
| Lobby | `com.unity.services.lobby` | Room creation, matchmaking |
| Relay | `com.unity.services.relay` | NAT traversal for P2P |
| Cloud Save | `com.unity.services.cloudsave` | Server-side player data |
| Leaderboards | `com.unity.services.leaderboards` | Ranked scoreboards |
| Economy | `com.unity.services.economy` | Virtual currencies, purchases |
| Analytics | `com.unity.services.analytics` | Player behavior tracking |
| Matchmaker | `com.unity.services.matchmaker` | Skill-based matchmaking |
Initialize UGS before using any service:
```csharp
await UnityServices.InitializeAsync();
await AuthenticationService.Instance.SignInAnonymouslyAsync();
```
## Firebase and PlayFab
Use Firebase for indie/mobile projects needing Realtime Database, Cloud Functions, and FCM push notifications. Use PlayFab for LiveOps-heavy games needing player segmentation, A/B testing, and automated rule processing. Both provide Unity SDKs via their respective download pages.
## Additional Resources
### Reference Files
- **`references/netcode-advanced.md`** -- Client prediction and reconciliation implementation, interest management, network LOD, bandwidth optimization, custom serialization, transport layer configuration
- **`references/backend-services.md`** -- Detailed UGS setup walkthroughs, Firebase/PlayFab integration patterns, REST API architecture, authentication flows, leaderboard and economy implementation
Related in Design
contribute
IncludedLocal-only OSS contribution command center. Auto-refreshes the user's in-flight PR and issue state on invoke so conversations start with full context — no need to brief Claude on what's in flight. Helps the user find issues to contribute to on GitHub, builds per-repo dossiers of what each upstream expects (CLA, DCO, branch convention, AI policy, draft-first, review bots, issue templates), runs deterministic gates before any external action so AI-assisted contributions don't reach maintainers as slop. State is markdown-only: candidate files at ~/.contribute-system/candidates/, repo dossiers at ~/.contribute-system/research/, append-only event log at ~/.contribute-system/log.jsonl. No database, no cloud calls. Use when the user asks about their PRs / issues / contributions, wants to find new work to take on, claim an issue, build/refresh a repo's dossier, or draft a Design Issue or PR. Trigger with "/contribute", "what's my PR status", "find a contribution", "claim issue X", "draft a Design Issue for Y", "refresh dossier for Z".
architectural-analysis
IncludedUser-triggered deep architectural analysis of a codebase or scoped subtree across eight modes — information architecture, data flow, integration points, UI surfaces, interaction patterns, data model, control flow, and failure modes. This skill should be used when the user asks to "diagram this codebase," "map the architecture," "show the data flow," "give me an ERD," "trace control flow," "find the integration points," "verify the layout pattern," "audit the UX architecture," or any similar request whose primary deliverable is mermaid diagrams plus cited reports under docs/architecture/. Dispatches haiku/sonnet sub-agents in parallel for per-mode exploration, then verifies every citation mechanically before any node lands in a diagram. Not for one-off prose explanations of code (use code-explanation) or for high-level system design from scratch (use system-design).
mcp
IncludedModel Context Protocol (MCP) server development and tool management. Languages: Python, TypeScript. Capabilities: build MCP servers, integrate external APIs, discover/execute MCP tools, manage multi-server configs, design agent-centric tools. Actions: create, build, integrate, discover, execute, configure MCP servers/tools. Keywords: MCP, Model Context Protocol, MCP server, MCP tool, stdio transport, SSE transport, tool discovery, resource provider, prompt template, external API integration, Gemini CLI MCP, Claude MCP, agent tools, tool execution, server config. Use when: building MCP servers, integrating external APIs as MCP tools, discovering available MCP tools, executing MCP capabilities, configuring multi-server setups, designing tools for AI agents.
react-native-skia
IncludedDesign, build, debug, and optimise high-polish animated graphics in React Native or Expo using @shopify/react-native-skia, Reanimated, and Gesture Handler. Use when the user wants canvas-driven UI, shaders, paths, rich text, image filters, sprite fields, Skottie, video frames, snapshots, web CanvasKit setup, or performance tuning for custom motion-heavy elements such as loaders, hero art, cards, charts, progress indicators, particle systems, or gesture-driven surfaces. Also use when the user asks for fluid, glow, glass, blob, parallax, 60fps/120fps, or GPU-friendly animated effects in React Native, even if they do not explicitly say "Skia". Do not use for ordinary form/layout work with standard views.
plaid
IncludedProduct Led AI Development — guides founders from idea to launched product. Six capabilities: Idea (discover a product idea), Validate (pressure-test the idea against fatal flaws, problem reality, competition, and 2-week MVP feasibility), Plan (vision intake + document generation), Design (translate image references into a design.md spec), Launch (go-to-market strategy), and Build (roadmap execution). Use when someone says "PLAID", "plaid idea", "help me find an idea", "product idea", "idea from my business", "idea from my expertise", "plaid validate", "validate my idea", "pressure-test", "is this idea good", "find fatal flaws", "validate the problem", "plan a product", "define my vision", "generate a PRD", "product strategy", "plaid design", "design from image", "translate image to design", "create design.md", "extract design tokens", "plaid launch", "go-to-market", "launch plan", "GTM strategy", "launch playbook", "plaid build", "build the app", "start building", or "execute the roadmap".
nextjs-framer-motion-animations
IncludedAdds production-safe Motion for React or Framer Motion animations to Next.js apps, including reveal, hover and tap micro-interactions, whileInView, stagger, AnimatePresence, layout and layoutId transitions, reorder, scroll-linked UI, and lightweight route-content transitions. Use when the user asks to add, refactor, or debug Motion or Framer Motion in App Router or Pages Router codebases, especially around server/client boundaries, reduced motion, LazyMotion, bundle size, hydration, or route transitions. Avoid for GSAP-style timelines, WebGL or 3D scenes, heavy scroll storytelling, or CSS-only effects unless Motion is explicitly requested.