🐾PurrNet Docs
Example

Top Down Character Controller

A multiplayer top-down character with server-authoritative movement, jump, and animator sync — built from four focused scripts that each own exactly one responsibility.

Overview — how the scripts connect

This example splits the controller into four scripts so that each one is easy to read, test, and swap. The server owns all physics; clients send input only.

  • CharacterData — a ScriptableObject holding speed, rotation rate, jump force, and gravity. Create one asset per character type; no code changes needed.
  • PlayerInputHandler— reads Unity's Input system every frame and calls the matching [ServerRpc]. Guards with IsOwnerso only the local player's client sends input.
  • TopDownMovement — the only NetworkBehaviour in the system. It owns SyncVar<Vector2> _velocity and SyncVar<bool> _isGrounded, runs CharacterController physics on the server, and raises onMovementChanged on every client whenever state changes.
  • TopDownAnimator — subscribes to onMovementChanged and drives the Animator parameters. Zero network traffic — it reacts to the already-replicated SyncVar values.

The data flow for one input frame:

  1. Owner client reads WASD → calls CmdMove(dir).
  2. Server validates and writes _velocity.
  3. PurrNet replicates the SyncVar to every observer.
  4. onMovementChanged fires on all clients → TopDownAnimator updates the blend tree.

Top Down Controller — component map — hover a node to highlight its connections

GameObject
Player
Prefab (GameObject)
NetworkBehaviour
TopDownMovement
NetworkBehaviour
MonoBehaviour
PlayerInputHandler
MonoBehaviour
MonoBehaviour
TopDownAnimator
MonoBehaviour
ScriptableObject
CharacterData
ScriptableObject
has component
has component
has component
CmdMove / CmdStop / CmdJump
onMovementChanged
MoveSpeed / JumpForce
animation thresholds
SyncVar
ServerRpc
ObserversRpc
Event (↔ = subscribe + fire)
Data reference
Method / component ref
NetworkBehaviour
MonoBehaviour
ScriptableObject
struct
Built-in (PurrNet)

Script 1 — CharacterData (ScriptableObject)

A plain data asset with no runtime logic. Create one per character type in Assets → Create → PurrNet → CharacterData. Designers adjust values in the Inspector; no C# changes needed.

CharacterData.cs
using UnityEngine;

/// <summary>
/// Immutable per-character-type configuration asset.
/// Create via Assets → Create → PurrNet → CharacterData.
/// </summary>
[CreateAssetMenu(menuName = "PurrNet/CharacterData", fileName = "NewCharacterData")]
public class CharacterData : ScriptableObject
{
    /// <summary>Horizontal movement speed in units/second.</summary>
    [field: SerializeField] public float MoveSpeed     { get; private set; } = 5f;

    /// <summary>Degrees per second for rotation towards movement direction.</summary>
    [field: SerializeField] public float RotationSpeed { get; private set; } = 720f;

    /// <summary>Initial vertical velocity applied on jump.</summary>
    [field: SerializeField] public float JumpForce     { get; private set; } = 8f;

    /// <summary>Downward acceleration while airborne (should be negative).</summary>
    [field: SerializeField] public float Gravity       { get; private set; } = -20f;
}

Script 2 — PlayerInputHandler (MonoBehaviour)

Runs every frame on the owner's machine. The IsOwner guard at the top of Updateis the single rule that prevents every connected client from flooding the server with input for a character they don't control.

PlayerInputHandler.cs
using PurrNet;
using UnityEngine;

/// <summary>
/// Reads local player input every frame and forwards it to the server via RPC.
/// Only sends when this client is the owner — non-owners do nothing.
/// </summary>
public class PlayerInputHandler : MonoBehaviour
{
    [SerializeField] private TopDownMovement _movement;

    private void Update()
    {
        // Non-owners must never send input for another player's character.
        if (!_movement.IsOwner) return;

        Vector2 dir = new Vector2(
            Input.GetAxisRaw("Horizontal"),
            Input.GetAxisRaw("Vertical")
        ).normalized;

        if (dir.sqrMagnitude > 0.01f)
            _movement.CmdMove(dir);
        else
            _movement.CmdStop();

        if (Input.GetButtonDown("Jump"))
            _movement.CmdJump();
    }
}
Replace Input.GetAxisRawwith your project's input system (Unity Input System's InputAction.ReadValue<Vector2>(), etc.) — only this script needs to change.

Script 3 — TopDownMovement (NetworkBehaviour)

This is the only networked script. It holds two SyncVars and runs CharacterController.Move() inside a server-only Update. Because the CharacterController is driven on the server, position is naturally authoritative; PurrNet's NetworkTransform component handles position replication to remote clients automatically.

The onMovementChanged event is raised via the SyncVar onChanged callbacks, which run on every client (including the host) after replication — so sibling scripts never need to poll.

TopDownMovement.cs
using PurrNet;
using System;
using UnityEngine;

/// <summary>
/// Owns all networked movement state for one player character.
/// Server is the sole writer of velocity and grounded state.
/// All clients receive changes through SyncVar replication.
/// </summary>
public class TopDownMovement : NetworkBehaviour
{
    [SerializeField] private CharacterData _data;

    // SyncVar replicates every write to all observers automatically.
    private SyncVar<Vector2> _velocity   = new(Vector2.zero);
    private SyncVar<bool>    _isMoving   = new(false);
    private SyncVar<bool>    _isGrounded = new(true);

    private CharacterController _cc;
    private float               _verticalVelocity;

    // -----------------------------------------------------------------------
    // Public surface
    // -----------------------------------------------------------------------

    /// <summary>
    /// Fires on ALL clients when velocity or isMoving changes.
    /// Parameters: (velocity, isMoving)
    /// </summary>
    public event Action<Vector2, bool> onMovementChanged;

    /// <summary>True when CharacterController.isGrounded. Replicated.</summary>
    public bool IsGrounded => _isGrounded.value;

    // -----------------------------------------------------------------------
    // Lifecycle
    // -----------------------------------------------------------------------

    protected override void OnSpawned(bool asServer)
    {
        base.OnSpawned(asServer);
        _cc = GetComponent<CharacterController>();

        // Raise the event on every client whenever state changes.
        _velocity.onChanged  += (_, v) => onMovementChanged?.Invoke(v, _isMoving.value);
        _isMoving.onChanged  += (_, m) => onMovementChanged?.Invoke(_velocity.value, m);
    }

    protected override void OnDespawned(bool asServer)
    {
        base.OnDespawned(asServer);
        _velocity.onChanged  -= (_, v) => onMovementChanged?.Invoke(v, _isMoving.value);
        _isMoving.onChanged  -= (_, m) => onMovementChanged?.Invoke(_velocity.value, m);
    }

    // -----------------------------------------------------------------------
    // ServerRpcs — only the owning client may call these
    // -----------------------------------------------------------------------

    /// <summary>Starts movement in the given (normalized) direction.</summary>
    [ServerRpc(requireOwnership: true)]
    public void CmdMove(Vector2 direction)
    {
        _velocity.value = direction * _data.MoveSpeed;
        _isMoving.value = true;
    }

    /// <summary>Stops horizontal movement.</summary>
    [ServerRpc(requireOwnership: true)]
    public void CmdStop()
    {
        _velocity.value = Vector2.zero;
        _isMoving.value = false;
    }

    /// <summary>Applies jump force. No-op if already airborne.</summary>
    [ServerRpc(requireOwnership: true)]
    public void CmdJump()
    {
        if (!_isGrounded.value) return;
        _verticalVelocity = _data.JumpForce;
    }

    // -----------------------------------------------------------------------
    // Server-side physics tick
    // -----------------------------------------------------------------------

    private void Update()
    {
        // Physics runs on the server only; clients read replicated state.
        if (!isServer || _cc == null) return;

        // Gravity accumulation
        if (_cc.isGrounded) _verticalVelocity = Mathf.Max(_verticalVelocity, -2f);
        else                _verticalVelocity += _data.Gravity * Time.deltaTime;

        _isGrounded.value = _cc.isGrounded;

        // Build motion vector and move
        Vector3 horizontal = new Vector3(_velocity.value.x, 0f, _velocity.value.y);
        _cc.Move((horizontal + Vector3.up * _verticalVelocity) * Time.deltaTime);

        // Rotate to face the movement direction
        if (horizontal.sqrMagnitude > 0.01f)
        {
            Quaternion target = Quaternion.LookRotation(horizontal);
            transform.rotation = Quaternion.RotateTowards(
                transform.rotation, target,
                _data.RotationSpeed * Time.deltaTime);
        }
    }
}
Add a NetworkTransform component to the prefab alongside TopDownMovement. Without it the server moves the object correctly but remote clients see it frozen at spawn position.

Script 4 — TopDownAnimator (MonoBehaviour)

A plain MonoBehaviour — no networking at all. It subscribes to onMovementChanged in Start and feeds the three Animator parameters every time movement state changes. Because the event fires from a SyncVar callback it already runs locally on every client.

TopDownAnimator.cs
using UnityEngine;

/// <summary>
/// Pure visual script — drives the Animator from replicated movement state.
/// No network traffic: runs on every client from the SyncVar-backed event.
/// </summary>
public class TopDownAnimator : MonoBehaviour
{
    [SerializeField] private TopDownMovement _movement;

    private Animator _animator;

    // Cache parameter hashes to avoid per-frame string lookups.
    private static readonly int SpeedHash      = Animator.StringToHash("Speed");
    private static readonly int IsMovingHash   = Animator.StringToHash("IsMoving");
    private static readonly int IsGroundedHash = Animator.StringToHash("IsGrounded");

    private void Awake()    => _animator = GetComponent<Animator>();

    private void Start()    => _movement.onMovementChanged += HandleMovementChanged;

    private void OnDestroy() => _movement.onMovementChanged -= HandleMovementChanged;

    // -----------------------------------------------------------------------
    // Event handler — called on every client whenever movement state changes
    // -----------------------------------------------------------------------

    private void HandleMovementChanged(Vector2 velocity, bool isMoving)
    {
        _animator.SetFloat(SpeedHash,      velocity.magnitude);
        _animator.SetBool(IsMovingHash,    isMoving);
        _animator.SetBool(IsGroundedHash,  _movement.IsGrounded);
    }
}
The Animator requires three parameters: Speed (Float), IsMoving (Bool), and IsGrounded (Bool). Create a blend tree on Speed for walk/run transitions, and a transition from IsGrounded = false into a jump/fall state.

API Reference — TopDownMovement

ParameterTypeDefaultDescription
CmdMove(Vector2 direction)[ServerRpc] void—Sets the movement velocity on the server. direction must be normalized. Only the owner may call this.
CmdStop()[ServerRpc] void—Zeroes velocity and sets isMoving to false. Call when the input axis returns to zero.
CmdJump()[ServerRpc] void—Applies jump force if the character is grounded. No-op in the air.
onMovementChangedevent Action<Vector2, bool>—Fires on all clients whenever velocity or isMoving changes. Parameters: (velocity, isMoving).
IsGroundedbool—Read-only. Backed by SyncVar<bool> — true when CharacterController reports grounded.

Scene Setup

  1. Create a CharacterData asset: Assets → Create → PurrNet → CharacterData. Set MoveSpeed, JumpForce, and Gravity.
  2. On the player prefab, add a CharacterController component. Set its radius and height to match your model.
  3. Add TopDownMovement, PlayerInputHandler, TopDownAnimator, and a PurrNet NetworkTransform component to the prefab.
  4. Assign the CharacterData asset to TopDownMovement._data, wire PlayerInputHandler._movement and TopDownAnimator._movement to the same TopDownMovement.
  5. Create an Animator Controller with Speed (Float), IsMoving (Bool), and IsGrounded (Bool) parameters. Assign it to the Animator component on the model child.
  6. Register the prefab with PurrNet's NetworkManager and call SpawnPlayer() on connection.
Never call CmdMove or CmdJump from server-only code — they are requireOwnership: true ServerRpcs and will be rejected if the caller is not the owner. Use direct field assignment on the server instead.

Best Practices

Send normalised direction from PlayerInputHandler. Raw axis values let a cheater send magnitude > 1 and move faster than MoveSpeed allows. Alternatively validate magnitude server-side in CmdMove.
If you use a rigidbody instead of CharacterController, switch to PurrNet's NetworkRigidbody component and drive velocity via Rigidbody.linearVelocity on the server — the physics replication path is different.