Search Unity

Question How to serialize a System.Object for an RPC call?

Discussion in 'Netcode for GameObjects' started by CameronDWills, Jun 25, 2022.

  1. CameronDWills

    CameronDWills

    Joined:
    Feb 26, 2021
    Posts:
    91
    Code (CSharp):
    1.     [ClientRpc]
    2.     public void MapSelectClientRpc(params object[] args)
    3.     {
    4.         CustomEvent.Trigger(gameObject, (string)args[0], args.Skip(1).ToArray());
    5.     }
    I'm trying to implement this as my RPC call, but it's triggering the error:
    error  - MapSelectClientRpc - Don't know how to serialize Object[]. RPC parameter types must either implement INetworkSerializeByMemcpy or INetworkSerializable. If this type is external and you are sure its memory layout makes it serializable by memcpy, you can replace System.Object[] with ForceNetworkSerializeByMemcpy`1<System.Object[]>, or you can create extension methods for FastBufferReader.ReadValueSafe(this FastBufferReader, out System.Object[]) and FastBufferWriter.WriteValueSafe(this FastBufferWriter, in System.Object[]) to define serialization for this type.


    I've been trying to follow the documentation at INetworkSerializable | Unity Multiplayer Networking (unity3d.com) but I can't figure out how to implement it in my use case. How can I use this to override the serialization so I can pass in my object? (this object will only ever contain the accepted types, like string, int, enum, etc)
     
  2. itisMarcii_

    itisMarcii_

    Joined:
    Apr 5, 2022
    Posts:
    111
    Like the error suggests, you need to implement INetworkSerializeByMemcpy

    Like that:

    Code (CSharp):
    1. public struct SomethingToSend : INetworkSerializeByMemcpy
    2. {
    3.   public int SomeInt;
    4.   public bool SomeFloat
    5. }
    PS: I am not sure right now, but a NetworkVariable needs to be none-nullable, i expect that is also the case for RPC Messages.