Search Unity

Question INetworkSerializable, TypeLoadException: Invalid generic instantiation

Discussion in 'Multiplayer' started by miccalisto, Apr 23, 2023.

  1. miccalisto

    miccalisto

    Joined:
    Feb 20, 2018
    Posts:
    40
    I am trying to serialize a class, but I keep getting this error. What does it mean?

    These are the attributes of the class.
    Code (CSharp):
    1. protected int attack;
    2. protected int damage;
    3. protected int evasion;
    4. protected int defense;
    5. protected int hitPoints;
    6.  
    7. protected int garrisonMax;
    8. protected int garrison;
    9.  
    10. protected SettlementType type;
    11. protected GameObject garrisonDisplay;
    12. protected Tile tile;
    13. protected Combat combat;
    I am trying to serialize these fields, I was told the class doesnt have to serialize all its attributes, right?
    Code (CSharp):
    1. public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter
    2. {
    3.       // Serialize int fields
    4.       serializer.SerializeValue(ref attack);
    5.       serializer.SerializeValue(ref damage);
    6.       serializer.SerializeValue(ref evasion);
    7.       serializer.SerializeValue(ref defense);
    8.       serializer.SerializeValue(ref hitPoints);
    9.       serializer.SerializeValue(ref garrisonMax);
    10.       serializer.SerializeValue(ref garrison);
    11. }
    I get the error only when trying to use the class in a networkvariable like this. Even when only declared it's immediatelly givving the error.
    Code (CSharp):
    1. NetworkVariable<SettlementBase> settlementBaseNetwork = new();
    What should I do?
     
  2. CodeSmile

    CodeSmile

    Joined:
    Apr 10, 2014
    Posts:
    6,005
    Are any of these fields a generic type or contain a generic type? That‘s what I would be looking into given the error message.
     
  3. Sandiford

    Sandiford

    Joined:
    Aug 21, 2015
    Posts:
    3
    I had this error when trying to implement INetworkSerializable in a class, as you seem to be doing.

    Got past it by changing the class to a struct.

    Not sure if we can Network Serialize classes - would like to know.
     
  4. CodeSmile

    CodeSmile

    Joined:
    Apr 10, 2014
    Posts:
    6,005
    Good point. The docs only use struct in their example but it doesn't explicitly mention that struct is a requirement.

    There is also INetworkSerializeByMemcpy which naturally only works with a struct. And then there is a special managed serializer (?) further suggesting that INetworkSerializable is either for struct only, or that you have to do something else to serialize a managed class.