Search Unity

Bug Don't know how to serialize Material

Discussion in 'Netcode for GameObjects' started by Natank25, Jun 18, 2022.

  1. Natank25

    Natank25

    Joined:
    Feb 10, 2022
    Posts:
    26
    I have a code to set the material of a SkinnedMeshRenderer of a player randomly :

    Code (CSharp):
    1. private void SetRndSkin(Material material)
    2.     {
    3.         meshRenderer.material = material;
    4.     }
    5.  
    6.     [ServerRpc]
    7.     private void SetRndSkinServerRpc(Material material)
    8.     {
    9.         if (!IsLocalPlayer) SetRndSkin(material);
    10.         SetRndSkinClientRpc(material);
    11.     }
    12.  
    13.     [ClientRpc]
    14.     private void SetRndSkinClientRpc(Material material)
    15.     {
    16.         if (!IsLocalPlayer && !IsServer) SetRndSkin(material);
    17.     }
    But I get error

    Don't know how to serialize Material - implement INetworkSerializable, tag memcpyable struct with INetworkSerializeByMemcpy, or add an extension method for FastBufferWriter.WriteValueSafe to define serialization.

    How can I fix it
     
  2. CosmoM

    CosmoM

    Joined:
    Oct 31, 2015
    Posts:
    204
    When you pass a material to a function, you actually pass a reference to it – an address in the system's memory, and so something that is inherently local. Instead, make sure that each client already has a local reference to the material (for example load in an array of materials from your Resources folder in Start()), and when calling the client or server Rpcs pass in the name of the material that you want loaded, or an index to it.
     
  3. Natank25

    Natank25

    Joined:
    Feb 10, 2022
    Posts:
    26
    So I did that, but I still get the error. So I decided to use int instead of materials in the functions parameters. Now, when a client join, the host get the error "Object reference not set to an instance of an object" at the line where meshRenderer.material is changed