NetworkBehaviour
NetworkBehaviour extends NetworkIdentity with RPC dispatch, SyncVar support, and network lifecycle callbacks. It is the base class for almost every multiplayer script in PurrNet.
What NetworkBehaviour Adds
NetworkIdentity gives a GameObject a network ID and tracks its owner and observers. NetworkBehaviour builds on that foundation and adds:
- RPC methods —
[ServerRpc],[ObserversRpc],[TargetRpc] - Sync types —
SyncVar<T>,SyncList<T>,SyncDictionary<K,V>and more - Network lifecycle callbacks —
OnSpawned,OnDespawned,OnOwnerChanged - NetworkModules — attach reusable, non-MonoBehaviour network logic
If you need any of the above in a script, inherit from NetworkBehaviour instead of MonoBehaviour. The component still behaves exactly like a MonoBehaviour — it has Awake, Start, Update, etc. — but PurrNet recognises it.
Properties
| Parameter | Type | Default | Description |
|---|---|---|---|
isServer | bool | — | True when this code runs on the server instance. Use to guard server-only logic such as spawning, damage application, and physics authority. |
isClient | bool | — | True when this code runs on a connected client. Also true on a host (listen server) because the host acts as both. |
isOwner | bool | — | True only on the client that currently owns this object. Use to restrict local player input, camera attachment, and owner-auth SyncVar writes. |
IsController | bool | — | True if this machine is the owner, or if the server is running and no owner is assigned. Useful for scripts that should be driven by the owner when present, or the server when absent. |
owner | PlayerID? | — | Nullable ID of the current owner. Null when the object is server-controlled or unowned. |
isSpawned | bool | — | True once the object is live on the network. False during Awake and before OnSpawned fires. |
localPlayer | PlayerID | — | Shortcut to the local machine's PlayerID. Equivalent to networkManager.localPlayer. |
Lifecycle Callbacks
Override these protected virtual methods instead of Unity messages for anything that depends on network readiness.
using PurrNet;
using UnityEngine;
public class NetworkBehaviourLifecycle : NetworkBehaviour
{
protected override void OnSpawned(bool asServer)
{
// Fired after the object is registered on the network.
// asServer is true when this callback runs on the server.
// Safe to access isOwner, owner, and SyncVar values here.
base.OnSpawned(asServer); // always call base first
if (asServer)
InitServerState();
if (isOwner)
AttachCamera();
}
protected override void OnDespawned(bool asServer)
{
// Fired before the object is removed from the network.
// Unsubscribe events and release resources here.
base.OnDespawned(asServer);
if (isOwner)
DetachCamera();
}
protected override void OnOwnerChanged(PlayerID? previousOwner, PlayerID? newOwner)
{
// Fired on ALL clients when ownership transfers.
bool iAmNewOwner = newOwner.HasValue && newOwner == localPlayer;
GetComponent<PlayerInputHandler>().enabled = iAmNewOwner;
nameplate.text = newOwner.HasValue
? $"Player {newOwner.Value}"
: "Unowned";
}
}Always call base.OnSpawned()
OnSpawned internally to initialise SyncVars and modules. If you override without calling base.OnSpawned(asServer), sync types may not replicate correctly for late-joining clients.Awake vs OnSpawned for initialization
Awake runs before the object is registered with the network. Accessing isOwner, isServer, or a SyncVar .value in Awake returns incorrect defaults. Defer network-dependent initialisation to OnSpawned. Subscribing to SyncVar onChanged callbacks in Awake is safe — just do not read the value there.NetworkBehaviour vs NetworkModule
| Use | When |
|---|---|
NetworkBehaviour | The script must live on a specific GameObject (player, enemy, item), declares its own RPCs and SyncVars. Most networked scripts are NetworkBehaviours. |
NetworkModule | You want reusable, shareable network logic across multiple NetworkBehaviours — e.g. a generic health module or stamina module — without tying it to a MonoBehaviour lifecycle. |
Full Example — PlayerHealth
The following class demonstrates isServer guards, [ServerRpc] for client-initiated damage requests, SyncVar for health replication, and lifecycle callbacks working together.
using PurrNet;
using UnityEngine;
using System.Collections;
public class PlayerHealth : NetworkBehaviour
{
[SerializeField] private int maxHealth = 100;
[SerializeField] private float respawnDelay = 3f;
// Server writes, all clients read
private SyncVar<int> _health = new(100);
private SyncVar<bool> _isDead = new(false);
private HealthBar _healthBar;
private void Awake()
{
_healthBar = GetComponentInChildren<HealthBar>();
// Subscribe in Awake so we never miss the first sync
_health.onChanged += OnHealthChanged;
_isDead.onChanged += OnDeathStateChanged;
}
protected override void OnSpawned(bool asServer)
{
base.OnSpawned(asServer);
// Reset health to max each time this object spawns
if (asServer)
_health.value = maxHealth;
}
// ------ Client → Server ------
// requireOwnership: false so the server can also call this directly,
// and so game-world damage triggers (traps, AOE) can hit any player.
[ServerRpc(requireOwnership: false)]
public void CmdTakeDamage(int amount, RPCInfo info = default)
{
// Server validates: is the caller allowed to deal damage?
if (_isDead.value || amount <= 0) return;
_health.value = Mathf.Max(0, _health.value - amount);
if (_health.value == 0)
StartCoroutine(HandleDeath());
}
[ServerRpc(requireOwnership: false)]
public void CmdHeal(int amount, RPCInfo info = default)
{
if (_isDead.value) return;
_health.value = Mathf.Min(maxHealth, _health.value + amount);
}
// ------ Server-side logic ------
private IEnumerator HandleDeath()
{
// isServer guard — this coroutine only runs on the server
if (!isServer) yield break;
_isDead.value = true;
yield return new WaitForSeconds(respawnDelay);
_health.value = maxHealth;
_isDead.value = false;
// Teleport to a random spawn point
var spawn = SpawnManager.GetRandomPoint();
transform.position = spawn;
}
// ------ Client-side reactions ------
private void OnHealthChanged(int newHealth)
{
_healthBar.SetFill((float)newHealth / maxHealth);
if (isOwner)
HUDManager.Instance.SetHealthText(newHealth, maxHealth);
}
private void OnDeathStateChanged(bool dead)
{
playerModel.SetActive(!dead);
deathOverlay.SetActive(dead && isOwner);
}
}Guard SyncVar writes with isServer
if (isServer) (or ownerAuth: true for owner-driven state) to avoid silent no-ops when a client attempts an unauthorised write.