Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.

Bug Don't know how to serialize Material

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

  1. Natank25


    Feb 10, 2022
    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.     }
    6.     [ServerRpc]
    7.     private void SetRndSkinServerRpc(Material material)
    8.     {
    9.         if (!IsLocalPlayer) SetRndSkin(material);
    10.         SetRndSkinClientRpc(material);
    11.     }
    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


    Oct 31, 2015
    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


    Feb 10, 2022
    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