3rd Person Character Controller
A multiplayer third-person controller with walk/run, jump, and smooth rotation — server-authoritative movement via CharacterController, position sync via NetworkTransform, and Animator driven by SyncVar events.
Overview — how the scripts connect
This example uses five components on the player prefab. The key design decision is that ThirdPersonMovement owns all state and the other scripts react to it — reducing coupling and keeping each file small.
- ThirdPersonData — ScriptableObject with walk speed, run speed, jump force, gravity, and turn-smooth time. One asset per character type.
- PlayerInputHandler — MonoBehaviour that reads Unity input and calls
CmdMove/CmdJump. TheIsOwnerguard at the top ofUpdateensures only the local player's client sends input. - ThirdPersonMovement — the only custom
NetworkBehaviour. OwnsSyncVar<float> _speed,SyncVar<bool> _isRunning, andSyncVar<bool> _isGrounded. RunsCharacterController.Move()on the server, raisesonStateChangedeverywhere. - NetworkTransform — a built-in PurrNet component. Automatically replicates the transform position and rotation that
ThirdPersonMovementwrites each server frame. No code needed. - ThirdPersonAnimator — MonoBehaviour that subscribes to
onStateChangedand pushes three parameters to theAnimator. Zero network traffic.
Data flow for one input frame:
- Owner client reads WASD + Shift → calls
CmdMove(dir, isRunning). - Server calculates target speed, smooth-damps rotation, writes SyncVars.
- PurrNet replicates SyncVars and NetworkTransform position to all observers.
onStateChangedfires on all clients →ThirdPersonAnimatorupdates the blend tree in one call.
3rd Person Controller — component map — hover a node to highlight its connections
Script 1 — ThirdPersonData (ScriptableObject)
A pure data asset. Having separate walk and run speeds here means designers can tune them per character type without modifying any C# logic. TurnSmoothTime controls how snappily the character rotates to face the movement direction — lower values feel snappier, higher values feel more weighty.
using UnityEngine;
/// <summary>
/// Immutable configuration for a third-person character type.
/// Create via Assets → Create → PurrNet → ThirdPersonData.
/// </summary>
[CreateAssetMenu(menuName = "PurrNet/ThirdPersonData", fileName = "NewThirdPersonData")]
public class ThirdPersonData : ScriptableObject
{
/// <summary>Walk speed in units/second (no Shift held).</summary>
[field: SerializeField] public float WalkSpeed { get; private set; } = 3f;
/// <summary>Run speed in units/second (Shift held).</summary>
[field: SerializeField] public float RunSpeed { get; private set; } = 6f;
/// <summary>Initial vertical velocity applied on jump.</summary>
[field: SerializeField] public float JumpForce { get; private set; } = 8f;
/// <summary>Downward acceleration while airborne (negative value).</summary>
[field: SerializeField] public float Gravity { get; private set; } = -20f;
/// <summary>
/// Seconds to smooth-damp rotation to the target facing angle.
/// Lower = snappier turning.
/// </summary>
[field: SerializeField] public float TurnSmoothTime { get; private set; } = 0.12f;
}Script 2 — PlayerInputHandler (MonoBehaviour)
Sends input every frame, including a zero vector when the player is idle — this is intentional. It lets the server know the player has stopped and zeroes the speed SyncVar cleanly, which in turn triggers the animator transition back to idle.
using PurrNet;
using UnityEngine;
/// <summary>
/// Reads local player input and forwards it to the server via RPC.
/// Guards with IsOwner — non-owners skip Update entirely.
/// </summary>
public class PlayerInputHandler : MonoBehaviour
{
[SerializeField] private ThirdPersonMovement _movement;
private void Update()
{
if (!_movement.IsOwner) return;
Vector2 moveInput = new Vector2(
Input.GetAxisRaw("Horizontal"),
Input.GetAxisRaw("Vertical")
).normalized;
bool isRunning = Input.GetKey(KeyCode.LeftShift);
// Always send, even when zero — lets the server know the player stopped.
_movement.CmdMove(moveInput, isRunning);
if (Input.GetButtonDown("Jump"))
_movement.CmdJump();
}
}CmdMove when it differs.Script 3 — ThirdPersonMovement (NetworkBehaviour)
The Update inside ThirdPersonMovement runs only on the server (guarded by if (!isServer) return). This means the physics simulation is single-source-of-truth. After CharacterController.Move() updates transform.position and transform.rotation, the attached NetworkTransform component detects the change and automatically sends a position snapshot to all connected clients.
The three SyncVars fire their onChanged lambdas on every client after replication, which raises the unified onStateChanged event. This means ThirdPersonAnimator always sees the same state as the server — no lag from manual polling.
using PurrNet;
using System;
using UnityEngine;
/// <summary>
/// Server-authoritative third-person movement.
/// Owns three SyncVars (speed, isRunning, isGrounded) and drives
/// CharacterController physics exclusively on the server.
/// NetworkTransform handles position/rotation replication to all clients.
/// </summary>
public class ThirdPersonMovement : NetworkBehaviour
{
[SerializeField] private ThirdPersonData _data;
private SyncVar<float> _speed = new(0f);
private SyncVar<bool> _isRunning = new(false);
private SyncVar<bool> _isGrounded = new(true);
private CharacterController _cc;
private float _verticalVelocity;
private float _turnVelocity; // SmoothDampAngle reference
// -----------------------------------------------------------------------
// Public surface
// -----------------------------------------------------------------------
/// <summary>
/// Fires on ALL clients when any of speed, isRunning, or isGrounded changes.
/// Parameters: (speed, isRunning, isGrounded)
/// </summary>
public event Action<float, bool, bool> onStateChanged;
/// <summary>Current horizontal speed. Backed by a replicated SyncVar.</summary>
public float Speed => _speed.value;
/// <summary>True when the CharacterController is touching the ground.</summary>
public bool IsGrounded => _isGrounded.value;
// -----------------------------------------------------------------------
// Lifecycle
// -----------------------------------------------------------------------
protected override void OnSpawned(bool asServer)
{
base.OnSpawned(asServer);
_cc = GetComponent<CharacterController>();
_speed.onChanged += (_, s) => onStateChanged?.Invoke(s, _isRunning.value, _isGrounded.value);
_isRunning.onChanged += (_, r) => onStateChanged?.Invoke(_speed.value, r, _isGrounded.value);
_isGrounded.onChanged += (_, g) => onStateChanged?.Invoke(_speed.value, _isRunning.value, g);
}
protected override void OnDespawned(bool asServer)
{
base.OnDespawned(asServer);
_speed.onChanged -= (_, s) => onStateChanged?.Invoke(s, _isRunning.value, _isGrounded.value);
_isRunning.onChanged -= (_, r) => onStateChanged?.Invoke(_speed.value, r, _isGrounded.value);
_isGrounded.onChanged -= (_, g) => onStateChanged?.Invoke(_speed.value, _isRunning.value, g);
}
// -----------------------------------------------------------------------
// ServerRpcs
// -----------------------------------------------------------------------
/// <summary>
/// Sets speed and facing direction on the server.
/// direction should be normalized; isRunning toggles walk vs run speed.
/// </summary>
[ServerRpc(requireOwnership: true)]
public void CmdMove(Vector2 direction, bool isRunning)
{
bool moving = direction.sqrMagnitude > 0.01f;
float target = isRunning ? _data.RunSpeed : _data.WalkSpeed;
_speed.value = moving ? target : 0f;
_isRunning.value = moving && isRunning;
if (moving)
{
// Smoothly rotate toward movement direction
float targetAngle = Mathf.Atan2(direction.x, direction.y) * Mathf.Rad2Deg;
float angle = Mathf.SmoothDampAngle(
transform.eulerAngles.y, targetAngle,
ref _turnVelocity, _data.TurnSmoothTime);
transform.rotation = Quaternion.Euler(0f, angle, 0f);
}
}
/// <summary>Applies jump force. No-op while airborne.</summary>
[ServerRpc(requireOwnership: true)]
public void CmdJump()
{
if (!_isGrounded.value) return;
_verticalVelocity = _data.JumpForce;
}
// -----------------------------------------------------------------------
// Server-side physics tick
// -----------------------------------------------------------------------
private void Update()
{
if (!isServer || _cc == null) return;
// Gravity
if (_cc.isGrounded) _verticalVelocity = Mathf.Max(_verticalVelocity, -2f);
else _verticalVelocity += _data.Gravity * Time.deltaTime;
_isGrounded.value = _cc.isGrounded;
// Move forward and apply gravity
Vector3 motion = transform.forward * _speed.value
+ Vector3.up * _verticalVelocity;
_cc.Move(motion * Time.deltaTime);
// NetworkTransform picks up the transform change and replicates it.
}
}ThirdPersonMovement. If your character has a separate model child object with its own transform, add NetworkTransform to the root, not the model.Script 4 — ThirdPersonAnimator (MonoBehaviour)
Subscribes in Start and unsubscribes in OnDestroy — always pair these to avoid dangling delegate references on pooled objects.Animator.StringToHash in static fields avoids the per-frame overhead of string hashing for parameter lookups.
using UnityEngine;
/// <summary>
/// Drives the character Animator from replicated movement state.
/// Pure MonoBehaviour — no network traffic. Reacts to onStateChanged
/// which is backed by SyncVar callbacks and already runs on every client.
/// </summary>
public class ThirdPersonAnimator : MonoBehaviour
{
[SerializeField] private ThirdPersonMovement _movement;
private Animator _animator;
private static readonly int SpeedHash = Animator.StringToHash("Speed");
private static readonly int IsRunningHash = Animator.StringToHash("IsRunning");
private static readonly int IsGroundedHash = Animator.StringToHash("IsGrounded");
private void Awake() => _animator = GetComponent<Animator>();
private void Start() => _movement.onStateChanged += HandleStateChanged;
private void OnDestroy() => _movement.onStateChanged -= HandleStateChanged;
private void HandleStateChanged(float speed, bool isRunning, bool isGrounded)
{
_animator.SetFloat(SpeedHash, speed);
_animator.SetBool(IsRunningHash, isRunning);
_animator.SetBool(IsGroundedHash, isGrounded);
}
}Speed (Float), IsRunning (Bool), IsGrounded (Bool). A typical 3rd-person blend tree uses Speed on the X-axis (0 = idle, 3 = walk, 6 = run) and transitions to/from a Jump state on IsGrounded.Script 5 — NetworkTransform (Built-in PurrNet)
You do not write any code for this component — just add it to the prefab in the Inspector. PurrNet's NetworkTransformwatches the GameObject's transform each server frame. When position or rotation changes by more than its configured threshold it sends a snapshot to all observers.
Configure it in the Inspector:
- Sync Position / Sync Rotation — enable both for a character controller; disable rotation if you handle facing server-side only.
- Interpolation— enable to smooth out remote clients' movement between snapshots. Set interpolation time slightly above your server tick interval.
- Authority — leave on Server. The server writes the transform; NetworkTransform replicates it.
API Reference — ThirdPersonMovement
| Parameter | Type | Default | Description |
|---|---|---|---|
CmdMove(Vector2 direction, bool isRunning) | [ServerRpc] void | — | Sets the character's horizontal speed and facing angle on the server. Only the owner may call this. |
CmdJump() | [ServerRpc] void | — | Applies jump force if grounded. No-op while airborne. |
onStateChanged | event Action<float, bool, bool> | — | Fires on all clients when speed, isRunning, or isGrounded changes. Parameters: (speed, isRunning, isGrounded). |
Speed | float | — | Current movement speed in units/second. Backed by SyncVar<float>. |
IsGrounded | bool | — | True when CharacterController reports the character is on the ground. Backed by SyncVar<bool>. |
Scene Setup
- Create a ThirdPersonData asset and configure walk/run speeds, jump force, gravity, and turn smooth time.
- On the player prefab root, add a
CharacterController. Set its center, radius, and height to match the character capsule. - Add ThirdPersonMovement, PlayerInputHandler, ThirdPersonAnimator, and PurrNet's NetworkTransform to the prefab root.
- Assign
ThirdPersonDatatoThirdPersonMovement._data. WirePlayerInputHandler._movementandThirdPersonAnimator._movementto the sameThirdPersonMovementinstance. - Place the model as a child object with its own
Animatorcomponent. Create an Animator Controller withSpeed,IsRunning, andIsGroundedparameters and a locomotion blend tree. - Configure NetworkTransform: enable Sync Position and Sync Rotation, enable Interpolation, leave Authority on Server.
- Register the prefab with NetworkManager and spawn it on player connection.
transform.position of the local player only. Check IsOwnerin a camera controller script and activate the camera only for the local player so other clients don't see through the wrong camera.SmoothDampAngle relies on a ref float _turnVelocity field that persists between frames. If you pool and re-use player prefabs, reset _turnVelocity = 0 in OnSpawned to avoid the character snapping to a stale velocity on re-spawn.