Mirror, FishNet & Photon Fusion
Netcode for GameObjects is not the only way to network a Unity game. Three other libraries are widely used, and they make different trade-offs: Mirror (open source, simple, the successor of Unity's old UNET), FishNet (open source, with built-in prediction), and Photon Fusion (a commercial SDK with a hosted cloud, tick-based prediction and lag compensation). This lesson compares them briefly, shows their core syntax side by side, and runs a model of the trick they all share: attributes that a code generator turns into network messages.
The same player in three libraries
The job is the same in every library: the owning client sends its input, the server changes authoritative state, and state flows back to everyone.
Mirror uses [SyncVar] fields with optional hooks, [Command] for client → server and [ClientRpc] / [TargetRpc] for server → clients:
using Mirror;
using UnityEngine;
public class MirrorPlayer : NetworkBehaviour
{
[SyncVar(hook = nameof(OnHealthChanged))]
int health = 100;
void OnHealthChanged(int oldValue, int newValue) { /* update the HUD */ }
[Command] // client -> server; owner only by default
void CmdFire(Vector3 aim, NetworkConnectionToClient sender = null)
{
// sender is filled in by Mirror; validate cooldown and aim, then:
RpcPlayMuzzleFlash();
}
[ClientRpc] // server -> every observing client
void RpcPlayMuzzleFlash() { }
[TargetRpc] // server -> one client
void TargetShowHitMarker(NetworkConnectionToClient target) { }
}FishNet (v4) uses SyncVar<T> objects instead of attributes on fields, and [ServerRpc], [ObserversRpc], [TargetRpc]:
using FishNet.Object;
using FishNet.Object.Synchronizing;
using FishNet.Connection;
public class FishPlayer : NetworkBehaviour
{
private readonly SyncVar<int> _health = new SyncVar<int>(100);
private void Awake() => _health.OnChange += OnHealthChanged;
private void OnHealthChanged(int prev, int next, bool asServer) { }
[ServerRpc] // owner only by default; RequireOwnership = false to relax
private void Fire(UnityEngine.Vector3 aim, NetworkConnection caller = null)
{
// runs on the server: validate cooldown and aim, apply damage to the target's SyncVar
PlayMuzzleFlash();
}
[ObserversRpc(ExcludeOwner = true)]
private void PlayMuzzleFlash() { }
[TargetRpc]
private void ShowHitMarker(NetworkConnection target) { }
}Photon Fusion 2 is built around a fixed tick. You declare [Networked] properties, read input in FixedUpdateNetwork (called once per simulation tick, and called again for the same tick when Fusion re-simulates after a correction), and draw in Render:
using Fusion;
public class FusionPlayer : NetworkBehaviour
{
[Networked] public int Health { get; set; }
public override void Spawned() { if (HasStateAuthority) Health = 100; }
public override void FixedUpdateNetwork()
{
if (GetInput(out PlayerInputData input)) // your INetworkInput struct
{
transform.position += input.Move * 5f * Runner.DeltaTime; // predicted, then corrected
}
}
public override void Render() { /* interpolated visuals */ }
}How they compare
| Mirror | FishNet | Photon Fusion 2 | |
|---|---|---|---|
| Licence / cost | open source (MIT) | open source, optional paid tier | commercial SDK + Photon Cloud; check current plans |
| Topologies | server, host (listen server) | server, host | Dedicated Server, Client Host, Shared Mode (each client has authority over its own objects) |
| Replicated state | [SyncVar], SyncList, SyncDictionary |
SyncVar<T>, SyncList<T>, … |
[Networked] properties stored in tick snapshots |
| Messages | [Command], [ClientRpc], [TargetRpc] |
[ServerRpc], [ObserversRpc], [TargetRpc] |
RPCs plus an input struct per tick |
| Prediction / reconciliation | write it yourself | built in (replicate/reconcile methods) | built in (re-simulation of ticks) |
| Lag compensation | write it yourself | add-ons and your own code | built in (hitbox history) |
| Transport | pluggable (KCP by default, Telepathy, Steam, WebSockets…) | pluggable (Tugboat by default, others) | Photon's own, cloud relay |
| Interest management | per-object observers (spatial hashing component) | observer conditions (distance, scene, …) | area of interest |
How to choose, roughly:
- Mirror if you want the simplest mental model, a large community and full control, and your game tolerates server-authoritative movement without prediction (co-op, slower games) or you will write prediction yourself.
- FishNet if you want open source and prediction, and are willing to learn its tick and replicate/reconcile model.
- Fusion if you need fast-paced competitive play with prediction and lag compensation now, and accept a commercial service. Its Shared Mode is a quick start for casual games, but each client then owns its own state, so it trades cheat resistance for simplicity.
- Netcode for GameObjects (previous lesson) if you prefer Unity's first-party package and services.
Note: All of these change between major versions (Mirror's weaver rules, FishNet's prediction API, Fusion 1 → 2). Read the version notes before following an older tutorial.
What the attributes really do
None of these libraries send C# method calls over the wire. At build time a code generator (Mirror's Weaver, FishNet's code generator, NGO's IL post-processor, Fusion's weaver) rewrites each attributed method: the caller's version serializes the arguments into a message with a method id; the receiver's version reads the id, checks the rules (is the sender the owner? is this the server?) and calls your body. The model below does the same with reflection: an attribute names the direction and whether ownership is required, and a dispatcher refuses calls that break the rules.
using System;
using System.Linq;
using System.Reflection;
[AttributeUsage(AttributeTargets.Method)]
class ServerCallAttribute : Attribute { public bool RequireOwnership = true; }
class Player
{
public int OwnerId;
public int Ammo = 2;
public Player(int owner) => OwnerId = owner;
[ServerCall] public void Fire(int sender) { Ammo--; Console.WriteLine(quot; Fire ok, ammo left {Ammo}"); }
[ServerCall(RequireOwnership = false)] public void Inspect(int sender) => Console.WriteLine(quot; client {sender} inspects player of client {OwnerId}");
public void GiveAmmo(int sender) { Ammo += 99; } // no attribute: not callable remotely
}
static class Dispatcher
{
// The "message" is (method id, sender). Ids come from a sorted list, like a weaver assigns them.
static readonly MethodInfo[] Remote = typeof(Player).GetMethods()
.Where(m => m.GetCustomAttribute<ServerCallAttribute>() != null)
.OrderBy(m => m.Name).ToArray();
public static int IdOf(string name) => Array.FindIndex(Remote, m => m.Name == name);
public static void Receive(Player target, int methodId, int sender)
{
if (methodId < 0 || methodId >= Remote.Length) { Console.WriteLine(quot; dropped: unknown method id {methodId} from client {sender}"); return; }
var m = Remote[methodId];
var attr = m.GetCustomAttribute<ServerCallAttribute>()!;
if (attr.RequireOwnership && sender != target.OwnerId) { Console.WriteLine(quot; dropped: client {sender} does not own this player ({m.Name})"); return; }
if (m.Name == "Fire" && target.Ammo <= 0) { Console.WriteLine(" dropped: no ammo (server-side rule)"); return; }
m.Invoke(target, new object[] { sender });
}
}
class Program
{
static void Main()
{
var p = new Player(owner: 1);
Console.WriteLine(quot;remote method ids: Fire={Dispatcher.IdOf("Fire")}, Inspect={Dispatcher.IdOf("Inspect")}, GiveAmmo={Dispatcher.IdOf("GiveAmmo")}");
(string label, int id, int sender)[] calls =
{
("owner fires", Dispatcher.IdOf("Fire"), 1),
("other client fires", Dispatcher.IdOf("Fire"), 2),
("other client inspects", Dispatcher.IdOf("Inspect"), 2),
("owner fires", Dispatcher.IdOf("Fire"), 1),
("owner fires again", Dispatcher.IdOf("Fire"), 1),
("hacked client sends id 7", 7, 1),
};
foreach (var c in calls)
{
Console.WriteLine(c.label + ":");
Dispatcher.Receive(p, c.id, c.sender);
}
}
}remote method ids: Fire=0, Inspect=1, GiveAmmo=-1
owner fires:
Fire ok, ammo left 1
other client fires:
dropped: client 2 does not own this player (Fire)
other client inspects:
client 2 inspects player of client 1
owner fires:
Fire ok, ammo left 0
owner fires again:
dropped: no ammo (server-side rule)
hacked client sends id 7:
dropped: unknown method id 7 from client 1
GiveAmmo has no id at all, so no packet can reach it; a forged id is dropped; ownership and game rules are checked on the server before your code runs. Every library above gives you the first two checks for free. The third (ammo, cooldowns, distances) is always yours: see Never Trust the Client.
Test yourself
Which library uses [Command] for client-to-server calls and [SyncVar(hook = ...)] for replicated fields?
- Netcode for GameObjects
- Mirror
- Photon Fusion
- FishNet v4
In Photon Fusion, why can FixedUpdateNetwork run more than once for the same tick?
- It is a bug
- Fusion re-simulates ticks after receiving authoritative state, to correct the predicted result
- Unity calls it from both Update and FixedUpdate
- It runs once per connected client
What does a networking library's weaver or code generator do with an RPC attribute?
- Sends the compiled method's IL to the server
- Rewrites the method so callers serialize the arguments with a method id and the receiver checks rules before running the body
- Nothing; attributes are only documentation
- Turns the method into a NetworkVariable