M
M
Mirror
Search…
SyncVar Hooks
The hook attribute can be used to specify a function to be called when the SyncVar changes value on the client.
    The Hook method must have two parameters of the same type as the SyncVar property. One for the old value, one for the new value.
    The Hook is always called after the property value is set. You don't need to set it yourself.
    The Hook only fires for changed values, and changing a value in the inspector will not trigger an update.
    As of version 11.1.4 (March 2020) and later, hooks can be virtual methods and overriden in a derived class.
Below is a simple example of assigning a random color to each player when they're spawned on the server. All clients will see all players in the correct colors, even if they join later.
Note: The signature for hook methods was changed in version 9.0 (Feb 2020) to having 2 parameters (old and new values). If you're on an older version, hook methods just have one parameter (new value).
1
using UnityEngine;
2
using Mirror;
3
4
public class PlayerController : NetworkBehaviour
5
{
6
[SyncVar(hook = nameof(SetColor))]
7
Color playerColor = Color.black;
8
9
// Unity makes a clone of the Material every time GetComponent().material is used.
10
// Cache it here and Destroy it in OnDestroy to prevent a memory leak.
11
Material cachedMaterial;
12
13
public override void OnStartServer()
14
{
15
base.OnStartServer();
16
playerColor = Random.ColorHSV(0f, 1f, 1f, 1f, 0.5f, 1f);
17
}
18
19
void SetColor(Color oldColor, Color newColor)
20
{
21
if (cachedMaterial == null)
22
cachedMaterial = GetComponent().material;
23
24
cachedMaterial.color = newColor;
25
}
26
27
void OnDestroy()
28
{
29
Destroy(cachedMaterial);
30
}
31
}
Copied!

Hook call order

Hooks are invoked in the order the syncvars are defined in the file.
1
public class MyBehaviour : NetworkBehaviour
2
{
3
[SyncVar]
4
int X;
5
6
[SyncVar(hook = nameof(Hook1))]
7
int Y;
8
9
[SyncVar(hook = nameof(Hook2))]
10
int Z;
11
}
Copied!
if X, Y, and Z are all set on the server at the same time then the call order will be:
    1.
    X value is set
    2.
    Y value is set
    3.
    Hook1 is called
    4.
    Z value is set
    5.
    Hook2 is called
Last modified 7mo ago
Copy link