Important: UNet is a deprecated solution, and a new Multiplayer and NetworkingThe Unity system that enables multiplayer gaming across a computer network. More info See in Glossary Solution (Netcode for GameObjects) is under development. For more information and next steps see the information on the Unity Netcode for GameObjects website. |
In most cases, the use of SyncVars is enough for your game scriptsA piece of code that allows you to create your own Components, trigger game events, modify Component properties over time and respond to user input in any way you like. More info
See in Glossary to serialize their state to clients. However in some cases you might require more complex serialization code. This page is only relevant for advanced developers who need customized synchronization solutions that go beyond Unity’s normal SyncVar feature.
To perform your own custom serialization, you can implement virtual functions on NetworkBehaviour to be used for SyncVar serialization. These functions are:
public virtual bool OnSerialize(NetworkWriter writer, bool initialState);
public virtual void OnDeSerialize(NetworkReader reader, bool initialState);
Use the initialState
flag to differentiate between the first time a GameObjectThe fundamental object in Unity scenes, which can represent characters, props, scenery, cameras, waypoints, and more. A GameObject’s functionality is defined by the Components attached to it. More info
See in Glossary is serialized and when incremental updates can be sent. The first time a GameObject is sent to a client, it must include a full state snapshot, but subsequent updates can save on bandwidth by including only incremental changes. Note that SyncVar hook functions are not called when initialState
is true; they are only called for incremental updates.
If a class has SyncVars, then implementations of these functions are added automatically to the class, meaning that a class that has SyncVars cannot also have custom serialization functions.
The OnSerialize
function should return true to indicate that an update should be sent. If it returns true, the dirty bits for that script are set to zero. If it returns false, the dirty bits are not changed. This allows multiple changes to a script to be accumulated over time and sent when the system is ready, instead of every frame.
GameObjects with the Network Identity component attached can have multiple scripts derived from NetworkBehaviour
. The flow for serializing these GameObjects is:
On the server:
Each NetworkBehaviour
has a dirty mask. This mask is available inside OnSerialize
as syncVarDirtyBits
Each SyncVar in a NetworkBehaviour
script is assigned a bit in the dirty mask.
Changing the value of SyncVars causes the bit for that SyncVar to be set in the dirty mask
Alternatively, calling SetDirtyBit()
writes directly to the dirty mask
NetworkIdentityA Networking component that allows you to assign an identity to your GameObject for the network to recognize it as a Local Player GameObject or a Server Only GameObject. More info
See in Glossary GameObjects are checked on the server as part of it’s update loop
If any NetworkBehaviours
on a NetworkIdentity
are dirty, then an UpdateVars
packet is created for that GameObject
The UpdateVars
packet is populated by calling OnSerialize
on each NetworkBehaviour
on the GameObject
NetworkBehaviours
that are not dirty write a zero to the packet for their dirty bits
NetworkBehaviours
that are dirty write their dirty mask, then the values for the SyncVars that have changed
If OnSerialize
returns true for a NetworkBehaviour
, the dirty mask is reset for that NetworkBehaviour
, so it does not send again until its value changes.
The UpdateVars
packet is sent to ready clients that are observing the GameObject
On the client:
an UpdateVars packet
is received for a GameObject
The OnDeserialize
function is called for each NetworkBehaviour
script on the GameObject
Each NetworkBehaviour
script on the GameObject reads a dirty mask.
If the dirty mask for a NetworkBehaviour
is zero, the OnDeserialize
function returns without reading any more
If the dirty mask is non-zero value, then the OnDeserialize
function reads the values for the SyncVars that correspond to the dirty bits that are set
If there are SyncVar hook functions, those are invoked with the value read from the stream.
So for this script:
public class data : NetworkBehaviour
{
[SyncVar]
public int int1 = 66;
[SyncVar]
public int int2 = 23487;
[SyncVar]
public string MyString = "Example string";
}
The following code sample demonstrates the generated OnSerialize
function:
public override bool OnSerialize(NetworkWriter writer, bool forceAll)
{
if (forceAll)
{
// The first time a GameObject is sent to a client, send all the data (and no dirty bits)
writer.WritePackedUInt32((uint)this.int1);
writer.WritePackedUInt32((uint)this.int2);
writer.Write(this.MyString);
return true;
}
bool wroteSyncVar = false;
if ((base.get_syncVarDirtyBits() & 1u) != 0u)
{
if (!wroteSyncVar)
{
// Write dirty bits if this is the first SyncVar written
writer.WritePackedUInt32(base.get_syncVarDirtyBits());
wroteSyncVar = true;
}
writer.WritePackedUInt32((uint)this.int1);
}
if ((base.get_syncVarDirtyBits() & 2u) != 0u)
{
if (!wroteSyncVar)
{
// Write dirty bits if this is the first SyncVar written
writer.WritePackedUInt32(base.get_syncVarDirtyBits());
wroteSyncVar = true;
}
writer.WritePackedUInt32((uint)this.int2);
}
if ((base.get_syncVarDirtyBits() & 4u) != 0u)
{
if (!wroteSyncVar)
{
// Write dirty bits if this is the first SyncVar written
writer.WritePackedUInt32(base.get_syncVarDirtyBits());
wroteSyncVar = true;
}
writer.Write(this.MyString);
}
if (!wroteSyncVar)
{
// Write zero dirty bits if no SyncVars were written
writer.WritePackedUInt32(0);
}
return wroteSyncVar;
}
The following code sample demonstrates the OnDeserialize
function:
public override void OnDeserialize(NetworkReader reader, bool initialState)
{
if (initialState)
{
this.int1 = (int)reader.ReadPackedUInt32();
this.int2 = (int)reader.ReadPackedUInt32();
this.MyString = reader.ReadString();
return;
}
int num = (int)reader.ReadPackedUInt32();
if ((num & 1) != 0)
{
this.int1 = (int)reader.ReadPackedUInt32();
}
if ((num & 2) != 0)
{
this.int2 = (int)reader.ReadPackedUInt32();
}
if ((num & 4) != 0)
{
this.MyString = reader.ReadString();
}
}
If a NetworkBehaviour
has a base class that also has serialization functions, the base class functions should also be called.
Note that the UpdateVar
packets created for GameObject state updates may be aggregated in buffers before being sent to the client, so a single transport layer packet may contain updates for multiple GameObjects.
When you visit any website, it may store or retrieve information on your browser, mostly in the form of cookies. This information might be about you, your preferences or your device and is mostly used to make the site work as you expect it to. The information does not usually directly identify you, but it can give you a more personalized web experience. Because we respect your right to privacy, you can choose not to allow some types of cookies. Click on the different category headings to find out more and change our default settings. However, blocking some types of cookies may impact your experience of the site and the services we are able to offer.
More information
These cookies enable the website to provide enhanced functionality and personalisation. They may be set by us or by third party providers whose services we have added to our pages. If you do not allow these cookies then some or all of these services may not function properly.
These cookies allow us to count visits and traffic sources so we can measure and improve the performance of our site. They help us to know which pages are the most and least popular and see how visitors move around the site. All information these cookies collect is aggregated and therefore anonymous. If you do not allow these cookies we will not know when you have visited our site, and will not be able to monitor its performance.
These cookies may be set through our site by our advertising partners. They may be used by those companies to build a profile of your interests and show you relevant adverts on other sites. They do not store directly personal information, but are based on uniquely identifying your browser and internet device. If you do not allow these cookies, you will experience less targeted advertising. Some 3rd party video providers do not allow video views without targeting cookies. If you are experiencing difficulty viewing a video, you will need to set your cookie preferences for targeting to yes if you wish to view videos from these providers. Unity does not control this.
These cookies are necessary for the website to function and cannot be switched off in our systems. They are usually only set in response to actions made by you which amount to a request for services, such as setting your privacy preferences, logging in or filling in forms. You can set your browser to block or alert you about these cookies, but some parts of the site will not then work. These cookies do not store any personally identifiable information.