🐾PurrNet Docs
Example

Monster Status System

A complete multiplayer monster health system with damage, healing, hit-flash effects, and a controller that wires everything together. Written for junior developers — each script has one clear responsibility.

Overview — how the scripts connect

This example is split into four scripts that each do exactly one job. Keeping responsibilities separate makes it easy to read, test, and swap parts without touching unrelated code.

  • MonsterData — a ScriptableObject that holds configuration (max HP, flash colour, flash duration). No logic, just data. Create one asset per monster type in your project.
  • MonsterHealth — the only script that owns networked state. It holds two SyncVar fields (_health and _isDead) and exposes them through events and read-only properties. Every other script reacts to its events rather than reading state directly.
  • MonsterHitEffect — a pure visual script. It subscribes toMonsterHealth.onHealthChanged and flashes the renderer colour for a short duration. Zero network traffic — the SyncVar callback already runs locally on every client.
  • MonsterController — the glue layer. It connects the health bar UI, triggers the death effect RPC, and schedules server-side destruction after the death animation plays out.

The flow for a single hit looks like this:

  1. Any client (player, trap, etc.) calls CmdTakeDamage().
  2. The server validates the call and subtracts HP from _health.
  3. PurrNet replicates the SyncVar change to every client.
  4. onHealthChanged fires on every client — MonsterHitEffect starts the flash coroutine and MonsterController updates the health bar.
  5. If HP reaches zero, onDied fires and the controller handles cleanup.

Monster Status System — component map — hover a node to highlight its connections

GameObject
Monster
Prefab (GameObject)
NetworkBehaviour
MonsterHealth
NetworkBehaviour
NetworkBehaviour
MonsterHitEffect
NetworkBehaviour
NetworkBehaviour
MonsterController
NetworkBehaviour
ScriptableObject
MonsterData
ScriptableObject
has component
has component
has component
onHealthChanged
onDied ↔
CmdTakeDamage()
[SerializeField]
HitColor / Duration
RpcPlayDeath()
SyncVar
ServerRpc
ObserversRpc
Event (↔ = subscribe + fire)
Data reference
Method / component ref
NetworkBehaviour
MonoBehaviour
ScriptableObject
struct
Built-in (PurrNet)

Script 1 — MonsterData (ScriptableObject)

MonsterData is a plain Unity ScriptableObject — no networking involved. Think of it as a recipe card: it describes what a monster type looks like and how it behaves, but it has no runtime state. Creating a separate asset for each monster type (Slime, Dragon, Boss, etc.) lets designers tweak values in the Inspector without touching any C# code.

The [CreateAssetMenu] attribute registers the asset in the Assets → Create → PurrNet menu so anyone on the team can make a new one without writing code.

MonsterData.cs
using PurrNet;
using UnityEngine;

/// <summary>
/// Immutable configuration data for a single monster type.
/// Create one asset per monster via Assets → Create → PurrNet → MonsterData.
/// </summary>
[CreateAssetMenu(menuName = "PurrNet/MonsterData", fileName = "NewMonsterData")]
public class MonsterData : ScriptableObject
{
    /// <summary>Display name shown in UI and debug logs.</summary>
    [field: SerializeField] public string MonsterName { get; private set; } = "Monster";

    /// <summary>Starting and maximum hit-points for this monster type.</summary>
    [field: SerializeField] public int MaxHealth { get; private set; } = 100;

    /// <summary>
    /// How long (in seconds) the hit-flash colour is shown before
    /// reverting to the normal colour.
    /// </summary>
    [field: SerializeField] public float FlashDuration { get; private set; } = 0.15f;

    /// <summary>Renderer colour applied for one FlashDuration when hit.</summary>
    [field: SerializeField] public Color HitColor { get; private set; } = Color.red;

    /// <summary>Renderer colour when the monster is alive and not flashing.</summary>
    [field: SerializeField] public Color NormalColor { get; private set; } = Color.white;
}

Script 2 — MonsterHealth (Networked)

MonsterHealth is the heart of the system. It extends NetworkBehaviour so PurrNet manages its lifetime on the network.

The two SyncVar fields are the only networked state in the entire example:

  • _health (SyncVar<int>) — the current HP value. The server writes it; every client reads the replicated copy.
  • _isDead (SyncVar<bool>) — flips to true once HP hits zero. Separating this flag from the HP value makes death checks instant without recalculating on every frame.

Two [ServerRpc] methods provide the public interface for damaging and healing. Both use requireOwnership: false so any game object — a player weapon, an AoE explosion, a trap — can call them without owning the monster.

Subscribing to SyncVar.onChanged in OnSpawned (instead ofAwake) is essential: the network layer is not ready until after spawn.

MonsterHealth.cs
using PurrNet;
using System;
using UnityEngine;

/// <summary>
/// Owns all networked health state for one monster instance.
/// Server is the sole writer; every client reads via SyncVar properties.
/// </summary>
public class MonsterHealth : NetworkBehaviour
{
    [SerializeField] private MonsterData _data;

    // SyncVar<T> automatically replicates value changes to all clients.
    private SyncVar<int>  _health = new(0);
    private SyncVar<bool> _isDead = new(false);

    // -----------------------------------------------------------------------
    // Public events — subscribe from MonsterHitEffect, MonsterController, UI
    // -----------------------------------------------------------------------

    /// <summary>
    /// Raised on ALL clients when HP changes.
    /// Parameters: (currentHP, maxHP)
    /// </summary>
    public event Action<int, int> onHealthChanged;

    /// <summary>Raised on ALL clients the moment the monster dies.</summary>
    public event Action onDied;

    // -----------------------------------------------------------------------
    // Public read-only properties
    // -----------------------------------------------------------------------

    /// <summary>Current hit-points. Backed by a SyncVar — always in sync.</summary>
    public int  CurrentHealth => _health.value;

    /// <summary>Maximum HP from MonsterData. Constant after spawn.</summary>
    public int  MaxHealth     => _data.maxHealth;

    /// <summary>True once health reaches zero.</summary>
    public bool IsDead        => _isDead.value;

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

    protected override void OnSpawned(bool asServer)
    {
        base.OnSpawned(asServer);

        // Subscribe to SyncVar change callbacks so every client raises events.
        _health.onChanged += HandleHealthChanged;
        _isDead.onChanged += HandleDeathChanged;

        // Only the server sets the initial value.
        if (asServer)
            _health.value = _data.maxHealth;
    }

    protected override void OnDespawned(bool asServer)
    {
        base.OnDespawned(asServer);

        _health.onChanged -= HandleHealthChanged;
        _isDead.onChanged -= HandleDeathChanged;
    }

    // -----------------------------------------------------------------------
    // ServerRpcs — callable by any game object, no ownership required
    // -----------------------------------------------------------------------

    /// <summary>
    /// Deals damage to this monster. Safe to call from traps, AoE,
    /// projectiles, or other players — server validates everything.
    /// </summary>
    [ServerRpc(requireOwnership: false)]
    public void CmdTakeDamage(int amount, RPCInfo info = default)
    {
        if (_isDead.value || amount <= 0) return;

        _health.value = Mathf.Max(0, _health.value - amount);

        if (_health.value == 0)
            _isDead.value = true;
    }

    /// <summary>
    /// Heals the monster up to MaxHealth. No-op when already dead.
    /// Useful for regeneration mechanics or a healer enemy type.
    /// </summary>
    [ServerRpc(requireOwnership: false)]
    public void CmdHeal(int amount)
    {
        if (_isDead.value || amount <= 0) return;

        _health.value = Mathf.Min(_data.maxHealth, _health.value + amount);
    }

    // -----------------------------------------------------------------------
    // SyncVar callbacks — run on every client (including host)
    // -----------------------------------------------------------------------

    private void HandleHealthChanged(int oldHP, int newHP)
    {
        onHealthChanged?.Invoke(newHP, _data.maxHealth);
    }

    private void HandleDeathChanged(bool wasAlive, bool isDead)
    {
        if (isDead)
            onDied?.Invoke();
    }
}

Script 3 — MonsterHitEffect (Visual Flash)

This script adds the hit-feedback that makes combat feel responsive. It listens for onHealthChangedand runs a coroutine that briefly changes every renderer's colour to HitColor before restoring the originals.

Key design decisions:

  • No RPCs needed. Because onHealthChanged is raised by a SyncVar callback, it already fires on every connected client. The flash is purely local and needs no additional network traffic.
  • Rapid-hit restart. If a new hit arrives while the flash coroutine is still running, it is stopped and restarted — so players always see feedback for every hit, even rapid ones.
  • Colours cached in Awake. Caching the original colours once avoids reading them from the material on every hit, which would allocate a new Material instance and cause unnecessary garbage.

The script references MonsterData directly via its own [SerializeField] field so it can read HitColor and FlashDuration without coupling to MonsterHealth's internals.

MonsterHitEffect.cs
using PurrNet;
using System.Collections;
using UnityEngine;

/// <summary>
/// Pure visual script — flashes all renderers to HitColor when
/// MonsterHealth reports a change, then restores the original colours.
/// No network traffic: driven entirely by the onHealthChanged event.
/// </summary>
public class MonsterHitEffect : NetworkBehaviour
{
    [SerializeField] private MonsterHealth _health;
    [SerializeField] private MonsterData   _data;   // same asset referenced by MonsterHealth

    /// <summary>All renderers that should flash on hit (body, eyes, etc.).</summary>
    [SerializeField] private Renderer[] _renderers;

    private Color[]   _originalColors;
    private Coroutine _flashCoroutine;

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

    private void Awake()
    {
        // Cache original colours before any flashing occurs.
        _originalColors = new Color[_renderers.Length];
        for (int i = 0; i < _renderers.Length; i++)
            _originalColors[i] = _renderers[i].material.color;
    }

    protected override void OnSpawned(bool asServer)
    {
        base.OnSpawned(asServer);
        _health.onHealthChanged += HandleHealthChanged;
    }

    protected override void OnDespawned(bool asServer)
    {
        base.OnDespawned(asServer);
        _health.onHealthChanged -= HandleHealthChanged;
    }

    // -----------------------------------------------------------------------
    // Event handler
    // -----------------------------------------------------------------------

    private void HandleHealthChanged(int currentHP, int maxHP)
    {
        // If a flash is already running, restart it so rapid hits all register.
        if (_flashCoroutine != null)
            StopCoroutine(_flashCoroutine);

        _flashCoroutine = StartCoroutine(FlashRoutine());
    }

    // -----------------------------------------------------------------------
    // Flash coroutine
    // -----------------------------------------------------------------------

    private IEnumerator FlashRoutine()
    {
        SetColor(_data.HitColor);
        yield return new WaitForSeconds(_data.FlashDuration);
        RestoreColors();
        _flashCoroutine = null;
    }

    // -----------------------------------------------------------------------
    // Helpers
    // -----------------------------------------------------------------------

    private void SetColor(Color color)
    {
        foreach (var r in _renderers)
            r.material.color = color;
    }

    private void RestoreColors()
    {
        for (int i = 0; i < _renderers.Length; i++)
            _renderers[i].material.color = _originalColors[i];
    }
}

Script 4 — MonsterController (Core Connector)

MonsterController is the coordinator. It does not own any networked state — it simply wires the other pieces together and handles the one situation that requires a new RPC: the death sequence.

When onDied fires it does two things in order:

  1. Calls RpcPlayDeathEffect() — an [ObserversRpc] that tells every client to play particles and hide renderers at the same moment.
  2. On the server only, starts a coroutine that waits for _destroyDelay seconds (giving the death animation time to play) then calls Destroy(gameObject). PurrNet automatically syncs the despawn to all clients.

The health bar reference is optional — MonsterController uses _healthBar?.UpdateDisplay() (null-conditional operator) so the prefab still works in scenes without a UI canvas.

MonsterController.cs
using PurrNet;
using System.Collections;
using UnityEngine;

/// <summary>
/// Wires MonsterHealth, MonsterHitEffect, and the optional health-bar UI
/// together. Handles death: plays a visual effect on all clients, then
/// destroys the monster on the server after a short delay.
/// </summary>
public class MonsterController : NetworkBehaviour
{
    [Header("Components")]
    [SerializeField] private MonsterHealth _health;
    [SerializeField] private MonsterHitEffect _hitEffect;

    /// <summary>
    /// Optional UI health bar. Assign in the Inspector.
    /// MonsterController null-checks before calling it.
    /// </summary>
    [SerializeField] private HealthBarUI _healthBar;

    [SerializeField] private MonsterData _data;

    [Header("Death Settings")]
    [SerializeField] private ParticleSystem _deathParticles;
    [SerializeField] private Renderer[]     _renderers;
    [SerializeField] private float          _destroyDelay = 2f;

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

    protected override void OnSpawned(bool asServer)
    {
        base.OnSpawned(asServer);

        _health.onHealthChanged += HandleHealthChanged;
        _health.onDied          += HandleDeath;
    }

    protected override void OnDespawned(bool asServer)
    {
        base.OnDespawned(asServer);

        _health.onHealthChanged -= HandleHealthChanged;
        _health.onDied          -= HandleDeath;
    }

    // -----------------------------------------------------------------------
    // Health changed
    // -----------------------------------------------------------------------

    private void HandleHealthChanged(int currentHP, int maxHP)
    {
        // Health bar is optional — safe to leave unassigned in the Inspector.
        _healthBar?.UpdateDisplay(currentHP, maxHP);
    }

    // -----------------------------------------------------------------------
    // Death
    // -----------------------------------------------------------------------

    private void HandleDeath()
    {
        // Play the death visual on every client immediately.
        RpcPlayDeathEffect();

        // Only the server schedules the actual destruction.
        if (isServer)
            StartCoroutine(DestroyAfterDelay(_destroyDelay));
    }

    /// <summary>
    /// Plays particle burst and hides renderers on all clients.
    /// Called automatically by HandleDeath().
    /// </summary>
    [ObserversRpc]
    private void RpcPlayDeathEffect()
    {
        if (_deathParticles != null)
            _deathParticles.Play();

        foreach (var r in _renderers)
            r.enabled = false;
    }

    // -----------------------------------------------------------------------
    // Helpers
    // -----------------------------------------------------------------------

    private IEnumerator DestroyAfterDelay(float delay)
    {
        yield return new WaitForSeconds(delay);
        Destroy(gameObject); // PurrNet syncs despawn to all clients
    }
}

Bonus — HealthBarUI helper

MonsterController references a HealthBarUIcomponent. Here is a minimal implementation using Unity's built-in Slider. Replace it with whatever widget your project uses — just keep the UpdateDisplay(int current, int max) signature.

HealthBarUI.cs
using UnityEngine;
using UnityEngine.UI;

/// <summary>
/// Minimal health-bar UI helper referenced by MonsterController.
/// Replace the Slider with whatever UI widget your project uses.
/// </summary>
public class HealthBarUI : MonoBehaviour
{
    [SerializeField] private Slider _slider;

    /// <summary>
    /// Updates the bar fill. Called by MonsterController on every HP change.
    /// </summary>
    /// <param name="current">Current hit-points.</param>
    /// <param name="max">Maximum hit-points.</param>
    public void UpdateDisplay(int current, int max)
    {
        if (_slider == null) return;
        _slider.value = max > 0 ? (float)current / max : 0f;
    }
}

API Reference

All public surface area of MonsterHealth — the only networked script in the system.

ParameterTypeDefaultDescription
TakeDamage(int amount)[ServerRpc] void—Subtracts amount from health. Validated server-side — callers don't need ownership.
Heal(int amount)[ServerRpc] void—Restores health up to MaxHealth. Has no effect if the monster is dead.
CurrentHealthint—Read-only current HP. Backed by a SyncVar<int> so all clients see the same value.
MaxHealthint—The max HP defined in MonsterData. Does not change at runtime.
IsDeadbool—True once health reaches zero. Backed by SyncVar<bool>.
onHealthChangedevent Action<int,int>—Fires on all clients when HP changes. Parameters: (currentHP, maxHP).
onDiedevent Action—Fires on all clients when the monster dies.

Scene Setup

Follow these steps to get the system running in a new scene:

  1. Create a MonsterData asset: Assets → Create → PurrNet → MonsterData. Set MonsterName, MaxHealth, HitColor, and FlashDuration.
  2. Create a monster prefab with a NetworkIdentity component (or it will inherit one from NetworkBehaviour). Add all four scripts: MonsterHealth, MonsterHitEffect, MonsterController, and optionally HealthBarUI.
  3. In the Inspector, drag the MonsterData asset into the _data field on both MonsterHealth and MonsterHitEffect.
  4. Assign the _renderers array on MonsterHitEffect to the renderers you want to flash (drag them from the hierarchy).
  5. Register the prefab in NetworkManager → Network Prefabs. PurrNet will not replicate objects whose prefabs are not registered.
  6. To spawn the monster at runtime, call Instantiate(monsterPrefab, position, rotation) on the server. PurrNet handles replication automatically.

requireOwnership: false on TakeDamage

Any game object can deal damage — traps, AoE explosions, other players — without needing to own the monster. The server validates everything, so there is no security risk and no awkward ownership transfers just to subtract a few hit-points.

Subscribe in OnSpawned, unsubscribe in OnDespawned

Never subscribe to SyncVar.onChanged in Awake — the network layer is not ready yet and the callback will never fire. Always pair every += in OnSpawned with a matching -= in OnDespawned to prevent memory leaks when the monster is destroyed and pooled objects are recycled.

Scene Setup checklist

Add all four scripts to the monster prefab. Assign MonsterData in the Inspector on both MonsterHealth and MonsterHitEffect. Register the prefab in NetworkManager → Network Prefabs. Spawn with Instantiate() on the server — PurrNet replicates automatically.