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

What is the proper way to alter a single material used on many objects?

Discussion in 'Editor & General Support' started by SuperUltraHyper, Apr 19, 2021.

  1. SuperUltraHyper

    SuperUltraHyper

    Joined:
    Sep 7, 2015
    Posts:
    112
    What is the proper way to alter a single material used on many objects?

    Details:

    I have a water material.

    It has a cubemap texture.

    I alter the assigned cubemap during runtime based on the time of day.

    If I use Renderer.sharedMaterials / Material.SetTexture("_CubeMap", Map); the documentation says to avoid this as it changes the values of the material in the project. And it checks it out of Perforce as well.... In addition to this, I am having trouble with the build and getting the material to update correctly. It looks and works fine in the editor (2020.3.1f1) but in a build the texture isn't being assigned / is missing.

    However, if I use Renderer.materials / Material.SetTexture("_CubeMap", Map);
    it creates an instance of each material, thus increasing draw calls. (Quest = Every draw call counts.) And it still has update issues in a build.

    So.... what should I do?

    Thanks in advance!
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,520
    By default when you instantiate X number of copies of a renderer, the .sharedMaterial(s) will point to the materials on disk.

    This is why the warning you get above and why you see the file change in P4.

    The best way to do this is to unique-ify the Material on the first copy of the renderer you make, assign the unique texture back to that render, AND to every subsequent copy of the renderer.

    You would also keep a copy of that Material, which is basically your shiny new "runtime shared" Material.

    When you make changes to this material, ALL renderers will instantly see that change.

    It works pretty slick this way and with only a minimum amount of muss and fuss setting it up in code.
     
    SuperUltraHyper likes this.
  3. SuperUltraHyper

    SuperUltraHyper

    Joined:
    Sep 7, 2015
    Posts:
    112
    Excellent. Thanks for the tip!
     
    Kurt-Dekker likes this.