There is a Video Tutorial covering some of the concepts covered in this page here
NetworkVariable is the way data can be synchronized between peers in abstracted ways. The data can be custom containers and complex structures such as inventory structs.
By default, Netcode comes with three different containers.
NetworkVariable container is built to store simple data types such as
ints. The List and Dictionary implementations are wrappers around the .NET equivalents. They are event-driven and have a list of events to be synced. The default implementations come with flexibility in terms of settings. Containers can be setup to sync Client To Server, Server To Client, or Bidirectional. It can also be set to target specific clients using custom delegates.
NetworkVariable container is a wrapper container around the value, the value has be accessed using the
NetworkDictionary implementations are primarily designed as samples showing how to create
INetworkVariable structures. The
NetworkVariable container is however considered production ready for simple types.
You must remember to add the
NetworkObject component to the game object to which your script belongs.
To create your own
NetworkVariable container, simply create a class with the
INetworkVariable interface and declare it as a field of a
NetworkBehaviour. To learn how to write your own containers for more complex structures, see the
NetworkVariable implementation. To learn how to do custom delta encoding on complex structures. See the
NetworkVariable and its subclasses can only be written to by the server (
NetworkVariablePermission.ServerOnly). To change that set the permission to the desired value during initialization:
If you want values to be synced only once (at spawn), the built-in container's send rate can be set to a negative value.
NetworkVariable class is a generic, editor serialization is NOT supported, it is only available through editor scripts for viewing the values. To get proper serialization, a clone of the
NetworkVariable implementation has to be done for each type you wish to use. For example,
NetworkVariableInt where you replace all the usages of
The MLAPI provides a few default serializable implementations of the
NetworkVariable, they are called
T is the type.
The following example uses network replication variables and detects the change in a unit's health and notifies the client. You can perform a
Awake to subscribe the
OnValueChanged of the health variable, then unsubscribe
OnDestroy. The example exposes a
NetworkVariable to other classes so that they can hook into Health's
OnValueChange delegate or event, since
m_Health is a private field.