In this lesson, you will learn how to transmit custom, complex data structures over the network by implementing the INetworkSerializable interface for your RPC parameters.
When you trigger a ServerRpc or ClientRpc, Unity’s Netcode automatically serializes primitive types like int, float, or bool. However, when you want to send a custom class or struct—such as an EquipmentData object containing various stats—you must teach the network how to read and write that data into the byte stream.
The Serialization Process
To send custom data, your struct or class must implement INetworkSerializable. This requires a single method, NetworkSerialize<T>, which acts as the bridge between your object's fields and the network buffer. You use a FastBufferReader to read data and a FastBufferWriter to write it.
Consider this example of a custom PlayerStats struct:
public struct PlayerStats : INetworkSerializable
{
public int Level;
public float Health;
public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
{
serializer.SerializeValue(ref Level);
serializer.SerializeValue(ref Health);
}
}
By defining this structure, you can now pass PlayerStats directly as a parameter in your RPC methods:
[ServerRpc]
public void UpdateStatsServerRpc(PlayerStats newStats)
{
// The complex struct is automatically serialized/deserialized
this.currentStats = newStats;
}
Why This Matters
If you try to pass a complex object without this interface, the RPC will fail at runtime because the network stack doesn't know how to translate your object into a sequence of bits. By manually defining the serialization order, you ensure that the server and client interpret the data identically. Furthermore, this method is significantly more efficient than converting your data to a JSON string, as it keeps the packet size minimal—crucial for maintaining the low-latency performance we established in our earlier lessons on bandwidth optimization.
Key Takeaway: By implementing INetworkSerializable on your custom data types, you enable seamless transmission of complex objects through RPCs while maintaining strict control over network traffic efficiency.