Replace stripped-player spectator with a minimal dedicated prefab

Mid-match joiners now spawn a dedicated empty Spectator prefab (NetworkObject
+ SpectatorSetup only) instead of a fully stripped Player prefab. The FreeCam
rig is a standalone scene object in Main, so the spectator needs no avatar body,
renderer, collider, or CharacterController -- eliminating the leftover-body
artifact and the fragile per-peer strip path entirely.

- SpectatorSetup.cs (new): owner binds GameModeManager.BindSpectator (FreeCam-only)
- Spectator.prefab (new): empty avatar (Transform + NetworkObject + SpectatorSetup),
  registered in DefaultNetworkPrefabs, wired on MatchManager in Main
- GameModeManager: add BindSpectator/BuildSpectatorModes; drop the spectator
  branch from BindLocalPlayer; ReleaseToNoPlayer frees the cursor on teardown
- MatchManager: independent entropy-seeded RNG for fair hunter pick (was sharing
  the global engine RNG and always landing on the same client); spawn the
  spectator prefab for mid-match joiners; cursor-safe return-to-Main teardown
- FreeCamController: guard IgnorePlayerCollision against a disabled capsule

Also bundled (unrelated user asset/UI edits): PaintHudPanel layout tuning,
font atlas (arialroundedmtprocyr_bold SDF), forestpack_foliage material.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
adminandClaude Opus 4.8 committed 2026-06-28 00:31:49 +02:00
1 parent be6db5b0a9
commit 91ce8ff329
12 files changed
+227 -1284

No files matched your search

+3 -1
View File
@@ -183,7 +183,9 @@ public class FreeCamController : MonoBehaviour
if (player)
{
var playerCC = player.GetComponent<CharacterController>();
if (playerCC)
// Only an enabled capsule can take part in a collision-ignore (a spectator's body has its CC
// disabled, and there is nothing to collide with there anyway).
if (playerCC && playerCC.enabled)
Physics.IgnoreCollision(_controller, playerCC, true);
}
}
+63 -6
View File
@@ -126,6 +126,35 @@ public class GameModeManager : MonoBehaviour
m.Bind(this);
}
/// <summary>Spectator mode set for a mid-match joiner: free-fly camera only (no player control, no
/// paint). They can fly around and watch, but not play, until the host ends the match (then they
/// respawn as a neutral lobby Player). Falls back to nothing if the scene has no free-cam rig.</summary>
private void BuildSpectatorModes()
{
_modes.Clear();
if (freeCam) _modes.Add(new FreeCamMode());
foreach (var m in _modes)
m.Bind(this);
}
/// <summary>
/// Binds a mid-match spectator. The spectator object is empty (no body/painter to bind), so just clear
/// the player/painter and switch the cycle to free-cam-only. The free-cam rig is a separate persistent
/// scene object that flies off Camera.main, so it needs nothing from the spectator. Called from
/// <see cref="SpectatorSetup"/> on the owning client.
/// </summary>
public void BindSpectator()
{
player = null;
painter = null;
PainterChanged?.Invoke(null);
ActiveMode?.Exit();
_activeIndex = -1;
BuildSpectatorModes();
SwitchTo(0);
}
/// <summary>
/// Binds the scene singletons (this manager, the orbit/first-person cameras, the painter) to the
/// locally-owned networked player after it spawns, then enters Player Control. Called from
@@ -135,19 +164,21 @@ public class GameModeManager : MonoBehaviour
public void BindLocalPlayer(PlayerCharacterController localPlayer)
{
if (!localPlayer) return;
var setup = localPlayer.GetComponent<NetworkPlayerSetup>();
player = localPlayer;
// The painter lives on the player (per-avatar), so bind the local one - UNCONDITIONALLY. On a
// lobby->match respawn the previous avatar is despawned and the role variant spawned in the same
// server frame; the old painter is Destroy-pending (still non-null) when this runs, so a
// `if (!painter)` guard would keep the stale reference and the new avatar's painter would never be
// mode-toggled - it would paint in every mode. Always re-point to the freshly spawned avatar.
// mode-toggled - it would paint in every mode. Always re-point to the fresh avatar.
painter = localPlayer.GetComponentInChildren<MeshPainter>(true);
PainterChanged?.Invoke(painter);
// Point the cameras at the avatar's follow target.
Transform camTarget = localPlayer.transform.Find("CameraTarget");
// Re-point the third-person orbit camera (Cinemachine Follow/LookAt) at the local avatar.
if (cameraInput)
{
var vcam = cameraInput.GetComponent<CinemachineCamera>();
@@ -161,9 +192,10 @@ public class GameModeManager : MonoBehaviour
ActiveMode?.Exit();
_activeIndex = -1;
// Lobby/neutral avatar (base Player prefab) -> full mode set; match avatar (Hunter/Hider
// variant) -> only its role's modes. Baked per prefab, so no replicated-phase timing race.
var setup = localPlayer.GetComponent<NetworkPlayerSetup>();
// Lobby/neutral avatar (base Player prefab) -> full mode set; match avatar (Hunter/Hider variant)
// -> only its role's modes. Scope is baked per prefab variant, so it follows the spawned avatar
// with no replicated-phase timing race. (Mid-match spectators take a separate, empty prefab and
// bind via BindSpectator, not here.)
if (setup && setup.ScopedModes)
BuildModes(setup.Role);
else
@@ -174,6 +206,31 @@ public class GameModeManager : MonoBehaviour
SwitchTo(0);
}
/// <summary>
/// Drops back to a player-less state when the local avatar is gone (disconnect / server shutdown
/// returns the session to the empty Main scene). Tears down the active mode so any FreeCam/First-Person
/// camera takeover is undone (which unlocks the cursor), clears the mode cycle, and - crucially - parks
/// the persistent orbit input in Disabled: it otherwise re-locks the cursor every frame while
/// AlwaysActive, so a one-off unlock would be reverted next frame and the OS cursor would stay captured
/// with no avatar to control. A reconnect's <see cref="BindLocalPlayer"/> restores everything.
/// </summary>
public void ReleaseToNoPlayer()
{
ActiveMode?.Exit();
_activeIndex = -1;
_modes.Clear();
player = null;
painter = null;
PainterChanged?.Invoke(null);
if (cameraInput)
cameraInput.LookMode = ThirdPersonOrbitInput.OrbitLookMode.Disabled;
// Belt-and-braces explicit release (covers the orbit input being absent/disabled).
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
}
private void Update()
{
if (_modes.Count == 0) return;
+33 -17
View File
@@ -39,8 +39,9 @@ using UnityEngine.InputSystem;
/// End / join / teardown:
/// - The host presses Esc -> <see cref="EndMatch"/>: Test Map is swapped back to Lobby and everyone is
/// respawned as the neutral Player. Server-gated, so only the host can end the match.
/// - A client that joins MID-MATCH is spectator-held (no avatar) - NGO still streams the running map to
/// it, but it doesn't play; it spawns into the lobby when the match ends.
/// - A client that joins MID-MATCH spawns as a SPECTATOR: a dedicated EMPTY prefab (no body/collider)
/// bound to free-cam-only, so it flies around the running map and watches but does not play. It
/// respawns as a neutral lobby Player when the match ends.
/// - On shutdown / disconnect (<see cref="ReturnToMainOnly"/>) every gameplay scene is unloaded so only
/// Main is left loaded & active. NGO's Dispose does NOT unload additively-synced scenes, so we do it.
///
@@ -68,6 +69,10 @@ public class MatchManager : MonoBehaviour
[SerializeField] private GameObject hunterPrefab;
[SerializeField] private GameObject hiderPrefab;
[Tooltip("Empty free-cam-only avatar spawned for a client that joins MID-MATCH. No body/collider - the " +
"free-cam rig is a separate scene object. Must be a registered network prefab.")]
[SerializeField] private GameObject spectatorPrefab;
[Header("Spawn")]
[Tooltip("World position lobby avatars are spawned at (raised a touch above the floor so gravity " +
"settles them). Per-client ring fan-out is applied on top (NetworkPlayerSetup.PlaceOnSpawnRing).")]
@@ -86,6 +91,12 @@ public class MatchManager : MonoBehaviour
private bool _sceneReady; // server-only: a gameplay scene (lobby/map) is loaded & active, so it is safe to spawn avatars
private bool _cleanedUp; // guards the shutdown scene-cleanup so a host (server+client stop) doesn't run it twice
// Role pick uses its OWN generator, seeded once from real entropy. UnityEngine.Random is a single
// engine-wide generator whose state at match-start can sit at the same point every fresh play
// session (nothing random consumed before it), which made the "random" hunter land on the same
// client every time. An independent System.Random decouples the pick from that shared global state.
private readonly System.Random _roleRng = new System.Random(System.Guid.NewGuid().GetHashCode());
private void Awake()
{
if (Instance && Instance != this) { Destroy(this); return; }
@@ -211,39 +222,38 @@ public class MatchManager : MonoBehaviour
// Lobby is loaded and active on the server: now it is safe to spawn the already-connected
// peers (the host, plus anyone who connected while the load was in flight).
_sceneReady = true;
foreach (ulong id in new List<ulong>(_net.ConnectedClientsIds)) SpawnPlayerFor(id, lobbySpawnCenter);
foreach (ulong id in new List<ulong>(_net.ConnectedClientsIds)) SpawnFor(id, _playerPrefab, lobbySpawnCenter);
}
// Server-side: a peer finished connecting. If a gameplay scene is already up, spawn it now;
// otherwise LoadLobbyRoutine (lobby) or RespawnAll (mid-transition) covers it (the PlayerObject
// guard in SpawnPlayerFor prevents a double spawn).
// guard in SpawnFor prevents a double spawn).
private void OnClientConnected(ulong clientId)
{
if (_net == null || !_net.IsServer) return;
// During a Lobby<->Test Map swap the active scene briefly falls back to Main (no floor); defer
// and let the respawn loop spawn this joiner once the target scene is loaded.
if (!_sceneReady || Phase == MatchPhase.Transitioning) return;
// Spectator-hold: a client that joins MID-MATCH gets NO avatar - they wait. NGO still streams the
// running map to their client (unavoidable), but they don't play in it. When the host ends the
// match, EndMatchSequence's respawn loop covers every connected client, so they spawn into the
// lobby with everyone else then.
if (Phase == MatchPhase.InMatch) return;
SpawnPlayerFor(clientId, lobbySpawnCenter);
// Mid-match joiner: spawn an empty SPECTATOR avatar (free-cam only) into the running map. They can
// fly around and watch but don't play. When the host ends the match, EndMatchSequence's respawn
// loop covers every connected client, so they turn into a neutral lobby Player with everyone else.
if (Phase == MatchPhase.InMatch) { SpawnFor(clientId, spectatorPrefab, matchSpawnCenter); return; }
SpawnFor(clientId, _playerPrefab, lobbySpawnCenter);
}
// Spawns the neutral Player avatar for a client into the currently active gameplay scene. No-op if
// the client already owns a player object (double-spawn guard) or has since disconnected.
private void SpawnPlayerFor(ulong clientId, Vector3 at)
// Spawns the given prefab as a client's player object into the currently active gameplay scene. No-op
// if the client already owns a player object (double-spawn guard) or has since disconnected.
private void SpawnFor(ulong clientId, GameObject prefab, Vector3 at)
{
if (!_playerPrefab)
if (!prefab)
{
Debug.LogError("[MatchManager] Player prefab missing (was NetworkConfig.PlayerPrefab assigned?) - cannot spawn.", this);
Debug.LogError("[MatchManager] Spawn prefab missing - cannot spawn.", this);
return;
}
if (!_net.ConnectedClients.TryGetValue(clientId, out var client)) return;
if (client.PlayerObject) return;
var go = Instantiate(_playerPrefab, at, Quaternion.identity);
var go = Instantiate(prefab, at, Quaternion.identity);
go.GetComponent<NetworkObject>().SpawnAsPlayerObject(clientId);
}
@@ -263,7 +273,7 @@ public class MatchManager : MonoBehaviour
if (ids.Count == 0) return;
Phase = MatchPhase.Transitioning;
ulong hunterId = ids[Random.Range(0, ids.Count)];
ulong hunterId = ids[_roleRng.Next(ids.Count)];
Debug.Log($"[MatchManager] Starting match. Hunter = client {hunterId}, {ids.Count} player(s).", this);
StartCoroutine(MatchSequence(hunterId));
@@ -376,6 +386,12 @@ public class MatchManager : MonoBehaviour
UnloadLocalIfLoaded(lobbySceneName);
UnloadLocalIfLoaded(matchSceneName);
// The local avatar is gone; drop the mode cycle back to a player-less state so the persistent
// orbit input stops re-locking the cursor (and any FreeCam/First-Person takeover is undone). Without
// this the OS cursor stays captured back in the empty Main scene.
var modes = FindFirstObjectByType<GameModeManager>(FindObjectsInactive.Include);
if (modes) modes.ReleaseToNoPlayer();
}
private void UnloadLocalIfLoaded(string sceneName)
+22
View File
@@ -0,0 +1,22 @@
using Unity.Netcode;
using UnityEngine;
/// <summary>
/// Per-avatar glue for a mid-match SPECTATOR. The spectator object is deliberately empty - no body, no
/// renderer, no collider, no controller - because the free-fly camera is a separate, persistent scene
/// object (in Main) that drives its own rig off Camera.main and needs nothing from this avatar. So the
/// spectator only has to exist as the owner's player object and flip the local mode set to free-cam-only.
/// The owner does that here; remote peers do nothing (there is no body to show or simulate). When the
/// host ends the match, MatchManager respawns this client as a neutral lobby Player.
/// </summary>
[DisallowMultipleComponent]
public class SpectatorSetup : NetworkBehaviour
{
public override void OnNetworkSpawn()
{
if (!IsOwner) return;
var manager = FindFirstObjectByType<GameModeManager>(FindObjectsInactive.Include);
if (manager) manager.BindSpectator();
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: afc5afb485e7fdb4e94dec910509cc97