Reorganize scripts into subfolders by responsibility

Move scripts under Assets/Scripts/ into Components, GameMode, Helper,
Network, Enum, Struct and ScriptableObject folders. Pure file moves
(plus folder .meta files); no code changes.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
adminandClaude Opus 4.8 committed 2026-07-02 15:02:15 +02:00
1 parent 382bfb36df
commit e23fae0c50
126 files changed
+112

No files matched your search

+118
View File
@@ -0,0 +1,118 @@
using UnityEngine;
using Unity.Netcode;
/// <summary>
/// First-person mode. The player keeps walking (WASD, camera-relative) but the camera moves to the
/// player's eye (the CameraTarget) with free mouse-look, and the player's mesh is hidden so the body
/// isn't seen from the inside. The orbit camera input is disabled while here so it doesn't fight for
/// the cursor; the <see cref="FirstPersonController"/> drives its own dedicated CinemachineCamera.
/// </summary>
public class FirstPersonMode : GameMode
{
public override string DisplayName => "First Person";
public override void Enter()
{
// Player stays fully controllable; only the view changes.
SetPlayerControl(true);
SetPainting(false);
SetOrbitInputEnabled(false);
if (Manager.FirstPerson)
Manager.FirstPerson.SetActive(true);
}
public override void Exit()
{
// Modes are Enter-only, so first-person must undo its own camera takeover (and unhide the mesh)
// here; the next mode's Enter restores the player/painter/look-mode state.
if (Manager.FirstPerson)
Manager.FirstPerson.SetActive(false);
SetOrbitInputEnabled(true);
if (Manager.CameraInput)
{
// Carry the first-person facing into the orbit camera so the next orbit mode (Paint / Player
// Control) keeps the current view angle instead of snapping back to the orbit's last-used angle.
// Camera.main still shows the first-person view this frame (the brain hasn't blended yet).
Manager.CameraInput.SyncToView();
}
}
// --- Hunter shooting -------------------------------------------------------------------------------
// A hunter in first person shoots a single ray from the camera centre on left-click (with a cooldown),
// but only during the SEEK sub-phase. A hit on an un-found hider is reported to the server, which
// validates and marks the hider found. Gated on the local avatar actually being a hunter role variant,
// so the legacy lobby first-person view never shoots.
private float _nextShootTime;
private static readonly RaycastHit[] _hits = new RaycastHit[32];
private static bool _hitsSaturated; // log-once: a saturated buffer can silently drop the true blocker
// Cached per bound avatar: CanShoot runs every Tick during a match.
private PlayerCharacterController _setupSource;
private NetworkPlayerSetup _setup;
public override void Tick()
{
if (!CanShoot()) return;
if (Time.time < _nextShootTime) return;
if (!InputUtil.LeftClickedThisFrame()) return;
_nextShootTime = Time.time + Mathf.Max(0f, MatchManager.Instance.ShootCooldown);
TryShoot();
}
private bool CanShoot()
{
var match = MatchManager.Instance;
if (!match || !match.MatchActive || match.LocalSubPhase != MatchManager.MatchSubPhase.Seek) return false;
var player = Manager.Player;
if (!player || !Manager.FirstPerson) return false;
if (player != _setupSource)
{
_setupSource = player;
_setup = player.GetComponent<NetworkPlayerSetup>();
}
return _setup && _setup.ScopedModes && _setup.Role == PlayerRole.Hunter;
}
private void TryShoot()
{
var match = MatchManager.Instance;
Transform cam = Manager.FirstPerson.transform; // FP vcam sits at the eye, facing the look direction
float range = Mathf.Max(0f, match.ShootRange);
int count = Physics.RaycastNonAlloc(cam.position, cam.forward, _hits, range, ~0, QueryTriggerInteraction.Ignore);
if (count == _hits.Length && !_hitsSaturated)
{
_hitsSaturated = true;
Debug.LogWarning($"FirstPersonMode: shot raycast buffer saturated ({count}); the nearest blocker may be missed.");
}
if (count == 0) return;
// Nearest-first so the shot stops at the first solid thing it meets (a wall blocks; a nearer avatar
// shields a farther one). The hunter's own body is skipped so looking down doesn't self-block.
System.Array.Sort(_hits, 0, count, RaycastDistanceComparer.Instance);
NetworkObject self = Manager.Player ? Manager.Player.GetComponent<NetworkObject>() : null;
for (int i = 0; i < count; i++)
{
var netObj = _hits[i].collider.GetComponentInParent<NetworkObject>();
if (netObj && self && netObj == self) continue;
if (!netObj || !netObj.IsPlayerObject) return; // first solid hit is world geometry -> blocked
var setup = netObj.GetComponent<NetworkPlayerSetup>();
if (setup && setup.Role == PlayerRole.Hider && !setup.IsFound)
match.ReportHit(netObj.OwnerClientId);
return; // the first non-self hit decides the shot
}
}
private sealed class RaycastDistanceComparer : System.Collections.Generic.IComparer<RaycastHit>
{
public static readonly RaycastDistanceComparer Instance = new RaycastDistanceComparer();
public int Compare(RaycastHit a, RaycastHit b) => a.distance.CompareTo(b.distance);
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: c514f1116e18b6c42907a5cb19aa228d
+31
View File
@@ -0,0 +1,31 @@
/// <summary>
/// Free-fly camera mode. The player is frozen in place, painting is off, and a dedicated
/// freecam (<see cref="FreeCamController"/> + its own CinemachineCamera) takes over: fly the
/// camera through the map with WASD/Q/E and the mouse, colliding with world geometry like the
/// player. The orbit camera input is disabled while here so it doesn't fight for the cursor.
/// </summary>
public class FreeCamMode : GameMode
{
public override string DisplayName => "Free Cam";
public override void Enter()
{
// Keep the player component alive (gravity/grounding) but reject input, like Paint mode.
SetPlayerControl(false);
SetPainting(false);
SetOrbitInputEnabled(false);
if (Manager.FreeCam)
Manager.FreeCam.SetActive(true);
}
public override void Exit()
{
// Modes are Enter-only, so freecam must undo its own camera takeover here; the next mode's
// Enter restores the player/painter/look-mode state.
if (Manager.FreeCam)
Manager.FreeCam.SetActive(false);
SetOrbitInputEnabled(true);
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: a221ef0b363824540993c714c0fc7385
+49
View File
@@ -0,0 +1,49 @@
/// <summary>
/// Base class for a high-level game mode handled by <see cref="GameModeManager"/>.
/// Modes are plain C# classes (not MonoBehaviours); Enter/Exit/Tick are driven
/// manually by the manager. Derive from this and register an instance in
/// GameModeManager.BuildModes().
/// </summary>
public abstract class GameMode
{
protected GameModeManager Manager { get; private set; }
/// <summary>Human-readable name (shown in logs).</summary>
public abstract string DisplayName { get; }
internal void Bind(GameModeManager manager) => Manager = manager;
/// <summary>Called once when this mode becomes active.</summary>
public virtual void Enter() { }
/// <summary>Called once when this mode stops being active.</summary>
public virtual void Exit() { }
/// <summary>Called every frame while this mode is active.</summary>
public virtual void Tick() { }
/// <summary>Enables the player component and sets whether it accepts movement input.</summary>
protected void SetPlayerControl(bool controlEnabled)
{
if (Manager.Player)
{
Manager.Player.enabled = true;
Manager.Player.ControlEnabled = controlEnabled;
}
}
/// <summary>Toggles painting on the mesh painter.</summary>
protected void SetPainting(bool on)
{
if (Manager.Painter)
Manager.Painter.PaintingEnabled = on;
}
/// <summary>Enables/disables the orbit camera input component. Off while a dedicated camera rig is
/// live: the orbit rig would otherwise keep grabbing the cursor and reading the mouse every frame.</summary>
protected void SetOrbitInputEnabled(bool on)
{
if (Manager.CameraInput)
Manager.CameraInput.enabled = on;
}
}
+2
View File
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 1dbd23638c056cc4db7ce7c0ffffe53c
+360
View File
@@ -0,0 +1,360 @@
using System.Collections.Generic;
using UnityEngine;
using Unity.Cinemachine;
#if ENABLE_INPUT_SYSTEM
using UnityEngine.InputSystem;
#endif
/// <summary>
/// Switches the game between high-level modes. The switch key (Tab) cycles to the next registered
/// mode. The mode set is scoped to the local avatar's <see cref="PlayerRole"/> when it spawns
/// (Hunter: First Person + Paint; Hider: Player Control + Paint + Free Cam); a non-networked scene
/// uses the full set. Attach to a single, persistent scene GameObject.
/// </summary>
[DisallowMultipleComponent]
public class GameModeManager : MonoBehaviour
{
[Header("Controlled Systems")]
[Tooltip("Player movement controller. Empty = found automatically.")]
public PlayerCharacterController player;
[Tooltip("Third-person orbit camera input. Empty = found automatically.")]
public ThirdPersonOrbitInput cameraInput;
[Tooltip("Mesh painter. Empty = found automatically.")]
public MeshPainter painter;
[Tooltip("Free-fly spectator camera. Empty = found automatically. Absent = Free Cam is left out of the cycle.")]
public FreeCamController freeCam;
[Tooltip("First-person camera. Empty = found automatically. Absent = First Person is left out of the cycle.")]
public FirstPersonController firstPerson;
[Header("Switching")]
[Tooltip("Key that cycles to the next mode.")]
#if ENABLE_INPUT_SYSTEM
public Key switchKey = Key.Tab;
#else
public KeyCode switchKey = KeyCode.Tab;
#endif
[Tooltip("Mode active at startup (0 = Player Control).")]
public int startModeIndex = 0;
public PlayerCharacterController Player => player;
public ThirdPersonOrbitInput CameraInput => cameraInput;
public MeshPainter Painter => painter;
public FreeCamController FreeCam => freeCam;
public FirstPersonController FirstPerson => firstPerson;
/// <summary>Raised after a mode switch finishes (the new mode's Enter has already run).
/// Argument = the now-active mode. Used by UI (e.g. the paint HUD) to follow the mode.</summary>
public event System.Action<GameMode> ModeChanged;
/// <summary>Raised when the painter the HUD should edit changes - i.e. when the local
/// networked avatar spawns and <see cref="BindLocalPlayer"/> binds its per-avatar painter.
/// With spawn-on-connect there is no painter at scene start, so the paint HUD follows this
/// to (re)bind its widgets to the live painter once it exists.</summary>
public event System.Action<MeshPainter> PainterChanged;
private readonly List<GameMode> _modes = new List<GameMode>();
private int _activeIndex = -1;
private bool _paused;
private int _resumeIndex = -1;
/// <summary>The currently active mode (null before startup).</summary>
public GameMode ActiveMode =>
(_activeIndex >= 0 && _activeIndex < _modes.Count) ? _modes[_activeIndex] : null;
private void Awake()
{
if (!player) player = FindFirstObjectByType<PlayerCharacterController>();
if (!cameraInput) cameraInput = FindFirstObjectByType<ThirdPersonOrbitInput>();
if (!painter) painter = FindFirstObjectByType<MeshPainter>();
// Include inactive so a freecam rig that starts disabled is still found and wired.
if (!freeCam) freeCam = FindFirstObjectByType<FreeCamController>(FindObjectsInactive.Include);
if (!firstPerson) firstPerson = FindFirstObjectByType<FirstPersonController>(FindObjectsInactive.Include);
BuildModes();
}
private void Start()
{
if (_modes.Count > 0)
SwitchTo(Mathf.Clamp(startModeIndex, 0, _modes.Count - 1));
}
/// <summary>Registers the modes for the current context. Without a role (no networked avatar yet,
/// or a non-networked scene) the full set is built from whichever rigs are present. With a role the
/// set is scoped to that side and ordered so index 0 is its intended start mode. Add new modes here.</summary>
private void BuildModes() => BuildModes(null);
private void BuildModes(PlayerRole? role)
{
_modes.Clear();
switch (role)
{
case PlayerRole.Hunter:
if (firstPerson) _modes.Add(new FirstPersonMode());
_modes.Add(new PaintMode());
break;
case PlayerRole.Hider:
if (player) _modes.Add(new PlayerControlMode());
_modes.Add(new PaintMode());
if (freeCam) _modes.Add(new FreeCamMode());
break;
default:
// No role: legacy full set, gated on whichever rigs exist (a player-less pre-spawn
// stays in Paint rather than a dead frozen Player Control).
if (player) _modes.Add(new PlayerControlMode());
_modes.Add(new PaintMode());
if (freeCam) _modes.Add(new FreeCamMode());
if (firstPerson) _modes.Add(new FirstPersonMode());
break;
}
foreach (var m in _modes)
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()
{
_paused = false;
_resumeIndex = -1;
ClearPlayerBindings();
TearDownActiveMode();
BuildSpectatorModes();
SwitchTo(0);
}
/// <summary>Drops the player/painter bindings and notifies painter-following UI.</summary>
private void ClearPlayerBindings()
{
player = null;
painter = null;
PainterChanged?.Invoke(null);
}
/// <summary>Exits the active mode and marks no mode active.</summary>
private void TearDownActiveMode()
{
ActiveMode?.Exit();
_activeIndex = -1;
}
/// <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
/// <see cref="NetworkPlayerSetup"/> on the owning client. Before this runs the scene has no player,
/// so the cycle sits in a player-less mode (Paint); this promotes it once the avatar exists.
/// </summary>
public void BindLocalPlayer(PlayerCharacterController localPlayer)
{
if (!localPlayer) return;
// A fresh bind is a definitive state reset - drop any modal pause so the new avatar starts live.
_paused = false;
_resumeIndex = -1;
var setup = localPlayer.GetComponent<NetworkPlayerSetup>();
player = localPlayer;
// Re-point UNCONDITIONALLY: on a lobby->match respawn the old painter is Destroy-pending (still
// non-null), so a `if (!painter)` guard would keep the stale reference and the new avatar's
// painter would never be mode-toggled.
painter = localPlayer.GetComponentInChildren<MeshPainter>(true);
PainterChanged?.Invoke(painter);
Transform camTarget = localPlayer.transform.Find("CameraTarget");
if (cameraInput)
{
var vcam = cameraInput.GetComponent<CinemachineCamera>();
if (vcam)
{
vcam.Follow = camTarget;
vcam.LookAt = camTarget;
// Follow (and its lossyScale) is live now - start at this avatar's scaled default zoom
// instead of inheriting the previous avatar's radius.
cameraInput.ResetZoom();
}
}
if (firstPerson)
firstPerson.SetPlayer(localPlayer);
// Tear down the pre-spawn (player-less) mode and rebuild scoped to this avatar's role.
TearDownActiveMode();
// Lobby avatar -> full set; match variant -> its role's modes. Scope is baked per prefab
// variant, so it follows the spawned avatar with no replicated-phase timing race.
if (setup && setup.ScopedModes)
BuildModes(setup.Role);
else
BuildModes(null);
// Index 0 is each set's intended start mode.
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()
{
_paused = false;
_resumeIndex = -1;
TearDownActiveMode();
_modes.Clear();
ClearPlayerBindings();
// The cycle is empty (no SwitchTo runs), so notify mode-following UI explicitly - otherwise the
// paint HUD (hides only via ModeChanged) would stay open after a shutdown during PaintMode.
ModeChanged?.Invoke(null);
if (cameraInput)
cameraInput.LookMode = ThirdPersonOrbitInput.OrbitLookMode.Disabled;
// Belt-and-braces explicit release (covers the orbit input being absent/disabled).
InputUtil.SetCursorLocked(false);
}
/// <summary>
/// Pauses/resumes local gameplay for a full-screen modal overlay (the Esc session panel). Suppresses
/// ALL local input and frees the cursor WITHOUT tearing down the mode cycle, so resuming re-enters
/// the exact mode that was active. Deliberately never Exits the active mode: the FP/free-cam vcam
/// keeps its priority, so the view stays frozen instead of blending back to the orbit camera (no
/// jump on open), and the resumed mode's snap-to-current-view is a no-op (no jump on close).
/// </summary>
public void SetPaused(bool paused)
{
if (paused == _paused) return;
_paused = paused;
if (paused)
{
_resumeIndex = _activeIndex;
_activeIndex = -1; // bookkeeping: no live mode while paused (Tick won't run)
// Freeze every input source without touching vcam priorities: dropping the FP/freecam
// `enabled` freezes their look in place; a Disabled orbit look-mode stops the per-frame
// cursor re-grab. At most one rig is ever enabled, so disabling both is safe.
if (player) player.ControlEnabled = false;
if (painter) painter.PaintingEnabled = false;
if (firstPerson) firstPerson.enabled = false;
if (freeCam) freeCam.enabled = false;
if (cameraInput)
{
cameraInput.enabled = true;
cameraInput.LookMode = ThirdPersonOrbitInput.OrbitLookMode.Disabled;
}
InputUtil.SetCursorLocked(false);
ModeChanged?.Invoke(null); // hide mode-following UI (the paint HUD) beneath the overlay
}
else
{
int resume = _resumeIndex;
_resumeIndex = -1;
if (resume >= 0 && resume < _modes.Count)
{
// Re-Enter the SAME mode (never Exited): its sync-to-current-view is a no-op -> no jump.
_activeIndex = resume;
ActiveMode.Enter();
ModeChanged?.Invoke(ActiveMode);
}
else
ModeChanged?.Invoke(ActiveMode);
}
}
private void Update()
{
if (_paused) return;
if (_modes.Count == 0) return;
// Resolution (the reveal window) is watch-only: force out of Paint and keep the switch key from
// re-entering. No restore needed - the end-of-match respawn rebuilds the cycle at index 0.
bool suppressPaint = PaintSuppressed();
if (suppressPaint && ActiveMode is PaintMode)
{
int fallback = FirstNonPaintFrom(0);
if (fallback >= 0) SwitchTo(fallback);
else if (painter) painter.PaintingEnabled = false; // degenerate paint-only set: at least stop painting
}
if (InputUtil.GameplayKeyPressed(switchKey))
{
int next = (_activeIndex + 1) % _modes.Count;
if (suppressPaint && _modes[next] is PaintMode)
{
int skip = FirstNonPaintFrom(next);
if (skip >= 0) next = skip;
}
SwitchTo(next);
}
ActiveMode?.Tick();
}
/// <summary>True while the local match is in its resolution (reveal) phase, during which painting is
/// disabled for the local player regardless of role.</summary>
private bool PaintSuppressed()
{
var match = MatchManager.Instance;
return match && match.MatchActive &&
match.LocalSubPhase == MatchManager.MatchSubPhase.Resolution;
}
/// <summary>First non-Paint mode index at or after <paramref name="start"/> (wrapping once through the
/// cycle); -1 if the set has no non-paint mode (a degenerate paint-only configuration).</summary>
private int FirstNonPaintFrom(int start)
{
for (int step = 0; step < _modes.Count; step++)
{
int i = (start + step) % _modes.Count;
if (!(_modes[i] is PaintMode)) return i;
}
return -1;
}
/// <summary>Activates the mode at <paramref name="index"/> (Exit old, Enter new).</summary>
public void SwitchTo(int index)
{
if (index < 0 || index >= _modes.Count || index == _activeIndex) return;
ActiveMode?.Exit();
_activeIndex = index;
ActiveMode.Enter();
Debug.Log($"[GameModeManager] Mode -> {ActiveMode.DisplayName}", this);
ModeChanged?.Invoke(ActiveMode);
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: 730466b26610d95498d22ab748d855a7
+29
View File
@@ -0,0 +1,29 @@
/// <summary>
/// Player stands still, the mesh is painted with the left mouse button. The
/// camera orbits only while the right mouse button is held, and the middle
/// mouse button pans the framing (a temporary offset to line up the model).
/// </summary>
public class PaintMode : GameMode
{
public override string DisplayName => "Paint";
public override void Enter()
{
SetPlayerControl(false);
if (Manager.CameraInput)
{
Manager.CameraInput.LookMode = ThirdPersonOrbitInput.OrbitLookMode.HoldRightMouseButton;
Manager.CameraInput.PanEnabled = true;
}
SetPainting(true);
}
public override void Exit()
{
// Leaving paint mode releases the middle-mouse pan; the orbit input then eases the framing home.
if (Manager.CameraInput)
Manager.CameraInput.PanEnabled = false;
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: a4815d31a23d2b14fb3fd22d9e13630d
@@ -0,0 +1,18 @@
/// <summary>
/// Player walks with WASD/Space, the camera orbits freely with the mouse.
/// Painting is disabled.
/// </summary>
public class PlayerControlMode : GameMode
{
public override string DisplayName => "Player Control";
public override void Enter()
{
SetPlayerControl(true);
if (Manager.CameraInput)
Manager.CameraInput.LookMode = ThirdPersonOrbitInput.OrbitLookMode.AlwaysActive;
SetPainting(false);
}
}
@@ -0,0 +1,2 @@
fileFormatVersion: 2
guid: c2f4d0884ba29d849afcaf6121027023