Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice
  3. Dismiss Notice

Resolved How Can I Define Custom Struct In NativeList

Discussion in 'Netcode for GameObjects' started by fisker, May 21, 2024.

  1. fisker

    fisker

    Joined:
    Nov 8, 2012
    Posts:
    2
    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
    upload_2024-5-21_21-22-42.png

    Code (CSharp):
    1. public struct BattleItemStruct: INetworkSerializable
    2. {
    3.     public Vector3 position;
    4.     public int entityId;
    5.     public int power;
    6.     public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
    7.     {
    8.         serializer.SerializeValue(ref position);
    9.         serializer.SerializeValue(ref entityId);
    10.         serializer.SerializeValue(ref power);
    11.     }
    12. }
    13.  
    14. public class BattleMsgData : INetworkSerializable
    15. {
    16.     public NativeList<BattleItemStruct> itemStructs = new NativeList<BattleItemStruct>();
    17.  
    18.     public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
    19.     {
    20.            serializer.SerializeValue(ref itemStructs);
    21.     }
    22.  
    23. }
     
  2. CodeSmile

    CodeSmile

    Joined:
    Apr 10, 2014
    Posts:
    6,922
    Check how it's implemented in NetworkList<T>

    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. ;)
     
  3. fisker

    fisker

    Joined:
    Nov 8, 2012
    Posts:
    2
    I
    Thanks for your sugesstion. That works.
    Code (CSharp):
    1.         int lenth = itemStructs.Length;
    2.         serializer.SerializeValue(ref lenth);
    3.         itemStructs.Length = lenth;
    4.         for (int i = 0; i < lenth; i++)
    5.         {
    6.             serializer.SerializeValue(ref itemStructs.ElementAt(i));
    7.         }
     
    CodeSmile likes this.