Gameplay State Controller
A networked game loop spanning two scenes: a City map where players vote to enter a dungeon, and a Dungeon scene with a five-phase state machine — Prepare, Vote to Start, Fight, End Fight, and Vote for Next Area.
Overview — two scenes, one game loop
This example teaches how to coordinate multiplayer game state across scene boundaries. The system has two distinct runtime phases:
- City Phase — players browse a map, select a dungeon, and vote as a group. When the vote passes, the server loads the dungeon scene for everyone.
- Dungeon Phase — a five-state machine runs on the server: a prepare countdown, a vote to start the fight, the fight itself, a celebration window, then a vote to continue or leave.
All state lives on the server and replicates via SyncVar and SyncDictionary. Clients display whatever the server says and send input only through [ServerRpc] calls.
City Phase — component map
City Phase — component map — hover a node to highlight its connections
Dungeon Phase — component map
Dungeon Phase — component map — hover a node to highlight its connections
Dungeon State Machine
DungeonStateManager drives five phases in a loop. Press Play to animate the cycle, or Step / click a node to jump to any phase.
Dungeon Phase State Machine — DungeonStateManager drives all transitions server-side
Script 1 — DungeonData (ScriptableObject)
A single asset per dungeon type. Holds everything needed to set up a run: the Unity scene name, player minimums, vote timers, and phase durations. Creating separate assets means designers can add new dungeons without changing any C#.
using UnityEngine;
/// <summary>
/// Static configuration for one dungeon type.
/// Create via Assets → Create → PurrNet → DungeonData.
/// </summary>
[CreateAssetMenu(menuName = "PurrNet/DungeonData", fileName = "NewDungeonData")]
public class DungeonData : ScriptableObject
{
/// <summary>Display name shown in MapUI and vote prompt.</summary>
[field: SerializeField] public string DungeonName { get; private set; } = "Dungeon";
/// <summary>Unity scene name to load for this dungeon.</summary>
[field: SerializeField] public string SceneName { get; private set; } = "DungeonScene";
/// <summary>Minimum connected players required before a vote can start.</summary>
[field: SerializeField] public int MinPlayers { get; private set; } = 2;
/// <summary>Seconds the vote window stays open before auto-failing.</summary>
[field: SerializeField] public float VoteDuration { get; private set; } = 15f;
/// <summary>Countdown (seconds) shown during the Prepare phase before voting opens.</summary>
[field: SerializeField] public float PrepareCountdown { get; private set; } = 10f;
/// <summary>Seconds of the EndFight celebration before the next-area vote opens.</summary>
[field: SerializeField] public float EndFightDelay { get; private set; } = 5f;
}Script 2 — GameStateManager (NetworkBehaviour)
The root coordinator. Owns a SyncVar<GameState> (City, VotingDungeon, LoadingDungeon, InDungeon) and holds the authority to load scenes. When VoteController reports a passed dungeon vote, DungeonSelector calls LoadDungeon() here, which fires an [ObserversRpc] that makes every client load the dungeon scene.
using PurrNet;
using System;
using UnityEngine;
using UnityEngine.SceneManagement;
/// <summary>
/// Top-level state machine: City ↔ Dungeon.
/// Owns scene-load authority and responds to VoteController results.
/// </summary>
public enum GameState { City, VotingDungeon, LoadingDungeon, InDungeon }
public class GameStateManager : NetworkBehaviour
{
[SerializeField] private DungeonData[] _availableDungeons;
private SyncVar<GameState> _state = new(GameState.City);
private SyncVar<string> _selectedDungeon = new(string.Empty);
// -----------------------------------------------------------------------
// Public surface
// -----------------------------------------------------------------------
/// <summary>Fires on ALL clients when the top-level state changes.</summary>
public event Action<GameState> onStateChanged;
public GameState CurrentState => _state.value;
// -----------------------------------------------------------------------
// Lifecycle
// -----------------------------------------------------------------------
protected override void OnSpawned(bool asServer)
{
base.OnSpawned(asServer);
_state.onChanged += (_, s) => onStateChanged?.Invoke(s);
}
// -----------------------------------------------------------------------
// Called by VoteController when a dungeon vote passes
// -----------------------------------------------------------------------
/// <summary>
/// Transition to LoadingDungeon and tell all clients to load the scene.
/// Only the server should call this — triggered internally by VoteController.
/// </summary>
public void LoadDungeon(string dungeonId)
{
if (!isServer) return;
_selectedDungeon.value = dungeonId;
_state.value = GameState.LoadingDungeon;
DungeonData data = System.Array.Find(_availableDungeons, d => d.DungeonName == dungeonId);
if (data != null)
RpcLoadScene(data.SceneName);
}
/// <summary>
/// Tells every client to load the dungeon scene.
/// PurrNet unloads the city scene automatically on the server.
/// </summary>
[ObserversRpc]
private void RpcLoadScene(string sceneName)
{
SceneManager.LoadSceneAsync(sceneName);
}
/// <summary>Called by DungeonStateManager when the dungeon run ends.</summary>
public void ReturnToCity()
{
if (!isServer) return;
_state.value = GameState.City;
RpcLoadScene("CityScene");
}
}Script 3 — VoteController (NetworkBehaviour)
A reusable vote engine used in both phases. It owns a SyncDictionary<string, bool>that maps each player's connection ID to their vote. Any change triggers an [ObserversRpc] that broadcasts a VoteSnapshot struct to all clients so the UI can update immediately.
The server auto-resolves the vote as soon as every connected player has voted, or closes it via a timeout coroutine, whichever comes first. The result is sent only once through the onVoteComplete event (server-only), so the caller —DungeonSelector or DungeonStateManager — can act on it without any additional RPC round-trip.
using PurrNet;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>Snapshot of one vote session sent to all clients on every change.</summary>
public readonly struct VoteSnapshot
{
public readonly int Yes;
public readonly int No;
public readonly int Total;
public readonly bool IsOpen;
public VoteSnapshot(int yes, int no, int total, bool isOpen)
{
Yes = yes; No = no; Total = total; IsOpen = isOpen;
}
}
/// <summary>
/// Generic multiplayer vote.
/// DungeonSelector and DungeonStateManager start votes;
/// all connected players cast YES/NO via CmdCastVote.
/// </summary>
public class VoteController : NetworkBehaviour
{
// Stores one vote per playerId. Automatically replicated to all observers.
private SyncDictionary<string, bool> _votes = new();
private SyncVar<bool> _isOpen = new(false);
private Coroutine _timeoutCoroutine;
// -----------------------------------------------------------------------
// Public surface
// -----------------------------------------------------------------------
/// <summary>
/// Fires on ALL clients whenever a vote is cast or the session opens/closes.
/// Parameters: current vote snapshot.
/// </summary>
public event Action<VoteSnapshot> onVoteChanged;
/// <summary>
/// Fires on the SERVER ONLY when the vote session closes with a result.
/// Parameters: (passed).
/// </summary>
public event Action<bool> onVoteComplete;
// -----------------------------------------------------------------------
// Server API — called by DungeonSelector or DungeonStateManager
// -----------------------------------------------------------------------
/// <summary>Opens a new vote session for <paramref name="durationSeconds"/> seconds.</summary>
public void StartVote(float durationSeconds)
{
if (!isServer) return;
_votes.Clear();
_isOpen.value = true;
BroadcastSnapshot();
_timeoutCoroutine = StartCoroutine(VoteTimeout(durationSeconds));
}
// -----------------------------------------------------------------------
// ServerRpc — any connected player can vote
// -----------------------------------------------------------------------
/// <summary>
/// Cast a YES or NO. Each player may vote once per session.
/// Server ignores duplicate votes from the same connection.
/// </summary>
[ServerRpc(requireOwnership: false)]
public void CmdCastVote(bool approve, RPCInfo info = default)
{
if (!_isOpen.value) return;
string playerId = info.sender.ToString();
_votes[playerId] = approve; // SyncDictionary replicates immediately
BroadcastSnapshot();
TryResolve();
}
// -----------------------------------------------------------------------
// Internals
// -----------------------------------------------------------------------
private void BroadcastSnapshot()
{
int yes = 0, no = 0;
foreach (var v in _votes.Values) { if (v) yes++; else no++; }
RpcUpdateUI(new VoteSnapshot(yes, no, _votes.Count, _isOpen.value));
}
[ObserversRpc]
private void RpcUpdateUI(VoteSnapshot snap)
{
onVoteChanged?.Invoke(snap);
}
private void TryResolve()
{
// Resolve immediately when every player has voted
if (_votes.Count < NetworkManager.connectedCount) return;
int yes = 0;
foreach (var v in _votes.Values) if (v) yes++;
CloseVote(yes > _votes.Count / 2);
}
private IEnumerator VoteTimeout(float seconds)
{
yield return new WaitForSeconds(seconds);
if (!_isOpen.value) yield break;
int yes = 0;
foreach (var v in _votes.Values) if (v) yes++;
CloseVote(yes > _votes.Count / 2);
}
private void CloseVote(bool passed)
{
if (_timeoutCoroutine != null) StopCoroutine(_timeoutCoroutine);
_isOpen.value = false;
BroadcastSnapshot();
onVoteComplete?.Invoke(passed);
}
}VoteController is generic — it does not know whether the vote is for a dungeon entry or a next-area decision. This means you can reuse it for any group decision in your game (kick vote, difficulty vote, etc.).Script 4 — DungeonSelector (NetworkBehaviour)
Lives in the City scene. When a player taps a dungeon button, MapUI calls CmdProposeDungeon(). The server stores the proposed ID, opens a vote, and waits. When onVoteComplete fires on the server with passed = true, it delegates to GameStateManager.LoadDungeon().
using PurrNet;
using UnityEngine;
/// <summary>
/// Runs in the City scene.
/// Lets any player propose a dungeon; opens a vote via VoteController;
/// tells GameStateManager to load the dungeon when the vote passes.
/// </summary>
public class DungeonSelector : NetworkBehaviour
{
[SerializeField] private DungeonData[] _dungeons;
[SerializeField] private VoteController _vote;
[SerializeField] private GameStateManager _gsm;
private string _proposedId = string.Empty;
protected override void OnSpawned(bool asServer)
{
base.OnSpawned(asServer);
if (asServer)
_vote.onVoteComplete += HandleVoteResult;
}
protected override void OnDespawned(bool asServer)
{
base.OnDespawned(asServer);
if (asServer)
_vote.onVoteComplete -= HandleVoteResult;
}
// -----------------------------------------------------------------------
// Called from MapUI button
// -----------------------------------------------------------------------
/// <summary>
/// Propose a dungeon for the group to vote on.
/// Opens a vote prompt on all clients.
/// </summary>
[ServerRpc(requireOwnership: false)]
public void CmdProposeDungeon(string dungeonId, RPCInfo info = default)
{
// Ignore proposals if a vote is already running
if (_gsm.CurrentState != GameState.City) return;
_proposedId = dungeonId;
DungeonData data = System.Array.Find(_dungeons, d => d.DungeonName == dungeonId);
if (data == null) return;
_vote.StartVote(data.VoteDuration);
}
// -----------------------------------------------------------------------
// Server-side: react to vote result
// -----------------------------------------------------------------------
private void HandleVoteResult(bool passed)
{
if (passed && !string.IsNullOrEmpty(_proposedId))
_gsm.LoadDungeon(_proposedId);
_proposedId = string.Empty;
}
}CmdProposeDungeon returns early if CurrentState != GameState.City — this prevents a second player from hijacking the vote mid-session.Script 5 — DungeonStateManager (NetworkBehaviour)
The heart of the dungeon loop. Runs entirely on the server via coroutines. Each phase either waits for a timer or for an external event (onVoteComplete or onAreaCleared) before advancing. Because transitions are driven by server coroutines and replicated via SyncVar<DungeonPhase>, every client sees the correct phase without any additional messaging.
The loop: Prepare (countdown) → VoteToStart → if passed, Fighting → EndFight → VoteNextArea → if passed, back to Prepare for the next area; if failed, server calls GameStateManager.ReturnToCity().
using PurrNet;
using System;
using System.Collections;
using UnityEngine;
/// <summary>Phases inside one dungeon run.</summary>
public enum DungeonPhase
{
Prepare, // Countdown before voting opens
VoteToStart, // Players vote to begin the fight
Fighting, // Enemies active; FightController is responsible
EndFight, // Brief celebration before next-area vote
VoteNextArea, // Players vote to continue or exit
}
/// <summary>
/// Server-authoritative state machine for the dungeon run.
/// Drives VoteController for the two vote phases and FightController
/// for the fight phase. Loops: VoteNextArea → Prepare (next area)
/// or exits back to city when the group votes NO.
/// </summary>
public class DungeonStateManager : NetworkBehaviour
{
[SerializeField] private DungeonData _data;
[SerializeField] private VoteController _vote;
[SerializeField] private FightController _fight;
[SerializeField] private GameStateManager _gsm;
private SyncVar<DungeonPhase> _phase = new(DungeonPhase.Prepare);
// -----------------------------------------------------------------------
// Public surface
// -----------------------------------------------------------------------
/// <summary>Fires on ALL clients when the dungeon phase changes.</summary>
public event Action<DungeonPhase> onPhaseChanged;
public DungeonPhase CurrentPhase => _phase.value;
// -----------------------------------------------------------------------
// Lifecycle
// -----------------------------------------------------------------------
protected override void OnSpawned(bool asServer)
{
base.OnSpawned(asServer);
_phase.onChanged += (_, p) => onPhaseChanged?.Invoke(p);
if (asServer)
{
_vote.onVoteComplete += HandleVoteResult;
_fight.onAreaCleared += HandleAreaCleared;
StartCoroutine(RunPreparePhase());
}
}
protected override void OnDespawned(bool asServer)
{
base.OnDespawned(asServer);
if (asServer)
{
_vote.onVoteComplete -= HandleVoteResult;
_fight.onAreaCleared -= HandleAreaCleared;
}
}
// -----------------------------------------------------------------------
// Phase coroutines — server only
// -----------------------------------------------------------------------
private IEnumerator RunPreparePhase()
{
_phase.value = DungeonPhase.Prepare;
yield return new WaitForSeconds(_data.PrepareCountdown);
_phase.value = DungeonPhase.VoteToStart;
_vote.StartVote(_data.VoteDuration);
// Waits for onVoteComplete → HandleVoteResult
}
private IEnumerator RunEndFightPhase()
{
_phase.value = DungeonPhase.EndFight;
yield return new WaitForSeconds(_data.EndFightDelay);
_phase.value = DungeonPhase.VoteNextArea;
_vote.StartVote(_data.VoteDuration);
// Waits for onVoteComplete → HandleVoteResult
}
// -----------------------------------------------------------------------
// Event handlers — server only
// -----------------------------------------------------------------------
private void HandleVoteResult(bool passed)
{
switch (_phase.value)
{
case DungeonPhase.VoteToStart:
if (passed)
{
_phase.value = DungeonPhase.Fighting;
_fight.ActivateArea();
}
else
{
// Failed to agree — re-open prepare phase
StartCoroutine(RunPreparePhase());
}
break;
case DungeonPhase.VoteNextArea:
if (passed)
StartCoroutine(RunPreparePhase()); // next area
else
_gsm.ReturnToCity();
break;
}
}
private void HandleAreaCleared()
{
if (_phase.value != DungeonPhase.Fighting) return;
StartCoroutine(RunEndFightPhase());
}
}Script 6 — FightController (NetworkBehaviour)
Tracks enemy count in a SyncVar<int> so every client can display a kill counter. When the count reaches zero it fires onAreaCleared on the server, which DungeonStateManager has subscribed to.
CmdReportEnemyKilled is requireOwnership: false so traps, AoE spells, and any other game object can report kills — not just the player who owns the FightController.
using PurrNet;
using System;
using UnityEngine;
/// <summary>
/// Manages enemies and objectives during the Fighting phase.
/// When all enemies are cleared it raises onAreaCleared so
/// DungeonStateManager can advance to EndFight.
/// </summary>
public class FightController : NetworkBehaviour
{
[SerializeField] private DungeonData _data;
private SyncVar<int> _enemiesRemaining = new(0);
// -----------------------------------------------------------------------
// Public surface
// -----------------------------------------------------------------------
/// <summary>Fires on the SERVER when every enemy in the area is dead.</summary>
public event Action onAreaCleared;
/// <summary>Fires on ALL clients when the enemy count changes.</summary>
public event Action<int> onEnemyCountChanged;
// -----------------------------------------------------------------------
// Called by DungeonStateManager when the Fighting phase begins
// -----------------------------------------------------------------------
/// <summary>Spawns enemies for the current area and starts tracking kills.</summary>
public void ActivateArea()
{
if (!isServer) return;
// TODO: spawn enemies from _data.EnemyWaves[currentWave]
_enemiesRemaining.value = 10; // placeholder
_enemiesRemaining.onChanged += (_, n) =>
{
onEnemyCountChanged?.Invoke(n);
if (n <= 0) onAreaCleared?.Invoke();
};
}
// -----------------------------------------------------------------------
// ServerRpc — enemies (or any game object) call this on death
// -----------------------------------------------------------------------
/// <summary>
/// Report one enemy killed. No ownership required — traps, AoE,
/// and other players can all trigger this.
/// </summary>
[ServerRpc(requireOwnership: false)]
public void CmdReportEnemyKilled(RPCInfo info = default)
{
if (_enemiesRemaining.value <= 0) return;
_enemiesRemaining.value--;
}
}API Reference
| Parameter | Type | Default | Description |
|---|---|---|---|
CmdProposeDungeon(string dungeonId) | [ServerRpc] void | — | Any client proposes a dungeon. Server opens a vote session via VoteController. |
CmdCastVote(bool approve) | [ServerRpc] void | — | Cast YES or NO. RPCInfo provides caller identity — each player votes once. |
CmdReportFightEnd() | [ServerRpc] void | — | FightController calls this when all enemies are cleared. Advances dungeon phase to EndFight. |
onStateChanged | event Action<GameState> | — | Fires on all clients whenever city/dungeon state changes. |
onPhaseChanged | event Action<DungeonPhase> | — | Fires on all clients whenever the dungeon phase advances. |
onVoteChanged | event Action<VoteSnapshot> | — | Fires on all clients with the current vote tally whenever a player votes. |
Scene Setup
- Create a DungeonData asset per dungeon: Assets → Create → PurrNet → DungeonData. Fill in SceneName, VoteDuration, PrepareCountdown, and EndFightDelay.
- In the City scene, create a Manager GameObject and add
GameStateManager,DungeonSelector, andVoteController. Register it with PurrNet's NetworkManager as a persistent object (do not destroy on scene load). - Add a MapUI MonoBehaviour with buttons for each
DungeonDataasset. Wire buttononClickto callDungeonSelector.CmdProposeDungeon(data.DungeonName). - In the Dungeon scene, create a Manager GameObject and add
DungeonStateManager,VoteController,FightController, andDungeonUI. - Wire
DungeonStateManager._voteandDungeonStateManager._fightin the Inspector. Assign the matchingDungeonDataasset to bothDungeonStateManager._dataandFightController._data. - Build the dungeon scene into your Build Settings and make sure its name matches
DungeonData.SceneNameexactly.
SceneManager.LoadSceneAsync from a client directly. All scene transitions must go through GameStateManager.RpcLoadScene (an ObserversRpc) so every client loads simultaneously. Asynchronous client-only loads cause desync.VoteController._votes is a SyncDictionary. Call _votes.Clear() at the start of every new vote session (already done in StartVote). Forgetting to clear it means late-joining players inherit old vote data.GameStateManager.onStateChanged and display the last known DungeonPhase via a separate SyncVar on DungeonStateManager that persists across the scene boundary.