Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

How to replace element in MeshRenderer.sharedMaterials

Discussion in 'AR/VR (XR) Discussion' started by unity_CmzqIOgMRopC4Q, Apr 25, 2019.

  1. unity_CmzqIOgMRopC4Q

    unity_CmzqIOgMRopC4Q

    Joined:
    Apr 5, 2019
    Posts:
    13
    We are using a object from the asset store that makes usage's of a mesh renderer with 32 materials in it. We need to implement functionality that makes it possible to replace 1 single material in the list, and keep the rest.

    I have tried several things, but I keep struggeling with the materials list, that is why I decided to ask you guys for help.

    Code (CSharp):
    1. public Material TestMaterial;
    2.  
    3. void Update()
    4. {
    5.        for (int i = 0; i < meshRenderer.sharedMaterials.Length; i++)
    6.        {
    7.        if (meshRenderer.sharedMaterials[i].name == "replaceableMat")
    8.        {
    9.              // Replace with TestMaterial
    10.        }
    11.        }
    12. }
    The above code is how I kinda want to use it.

    The TestMaterial object is not null, it is selected from the Unity Editor, so that is fine.

    Could someone give me some insight?

    Thanks in forward!
     
  2. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,859
    From the docs, it sounds like you can just modify this array and assign it back.

    Code (csharp):
    1. var mats = meshRenderer.sharedMaterials;
    2. mats[7] = someOtherMaterial;
    3. meshRenderer.sharedMaterials = mats;
     
    unity_CmzqIOgMRopC4Q likes this.