Since NetPacketProcessor does not support nested structs or classes by default, you must register custom type processors using RegisterNestedType. There are three ways to handle this:
1. Using static Serialize/Deserialize methods
For basic structs, provide static methods that use NetDataWriter and NetDataReader.
struct MyType {
public int Value1;
public static void Serialize(NetDataWriter writer, MyType mytype) => writer.Put(mytype.Value1);
public static MyType Deserialize(NetDataReader reader) => new MyType { Value1 = reader.GetInt() };
}
// Registration:
netPacketProcessor.RegisterNestedType(MyType.Serialize, MyType.Deserialize);
2. Implementing INetSerializable
For structs or classes, implement the INetSerializable interface. This is the most automated way.
struct MyType : INetSerializable {
public int Value1;
public void Serialize(NetDataWriter writer) => writer.Put(Value1);
public void Deserialize(NetDataReader reader) => Value1 = reader.GetInt();
}
// Registration:
netPacketProcessor.RegisterNestedType<MyType>();
3. Registering Classes with Constructors
If using a class instead of a struct, you must implement INetSerializable and provide a constructor factory to the registration method.
class MyType : INetSerializable {
public int Value1;
public void Serialize(NetDataWriter writer) => writer.Put(Value1);
public void Deserialize(NetDataReader reader) => Value1 = reader.GetInt();
}
// Registration (must provide constructor factory):
netPacketProcessor.RegisterNestedType<MyType>(() => new MyType());
// Example of Registering a custom type via static methods
struct MyType
{
public int Value1;
public string Value2;
public static void Serialize(NetDataWriter writer, MyType mytype)
{
writer.Put(mytype.Value1);
writer.Put(mytype.Value2);
}
public static MyType Deserialize(NetDataReader reader)
{
MyType res = new MyType();
res.Value1 = reader.GetInt();
res.Value2 = reader.GetString();
return res;
}
}
netPacketProcessor = new NetPacketProcessor();
netPacketProcessor.RegisterNestedType( MyType.Serialize, MyType.Deserialize );