How Can I Define Custom Struct In NativeList

When I Define Custom Struct With NativeList, I Got This Error, How Can I Fix It?
ArgumentException: Serialization has not been generated for type Unity.Collections.NativeList`1

public struct BattleItemStruct: INetworkSerializable
{
    public Vector3 position;
    public int entityId;
    public int power;
    public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
    {
        serializer.SerializeValue(ref position);
        serializer.SerializeValue(ref entityId);
        serializer.SerializeValue(ref power);
    }
}

public class BattleMsgData : INetworkSerializable
{
    public NativeList<BattleItemStruct> itemStructs = new NativeList<BattleItemStruct>();

    public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
    {
           serializer.SerializeValue(ref itemStructs);
    }

}

Check how it’s implemented in NetworkList

Apparently NativeList needs serialization by itself, you can’t passt the itemStructs as is but would rather have to serialize the following:

  • itemStructs.Length
  • each BattleItemStruct item

Note: it is bad practice to suffix types with, well, their type. It should be BattleItem not BattleItemStruct the same way you don’t name it BattleMsgDataClass. :wink:

I

Thanks for your sugesstion. That works.

        int lenth = itemStructs.Length;
        serializer.SerializeValue(ref lenth);
        itemStructs.Length = lenth;
        for (int i = 0; i < lenth; i++)
        {
            serializer.SerializeValue(ref itemStructs.ElementAt(i));
        }
1 Like