Search Unity

Question why are shaders instanced?

Discussion in 'Shaders' started by Shanti-AnyVerse, Jul 11, 2022.

  1. Shanti-AnyVerse

    Shanti-AnyVerse

    Joined:
    Dec 26, 2021
    Posts:
    24
    Hey all,
    Some of my objects in scene are using a material instance- as in the attached photo (and not the original material)
    I did not purposefully do this (don't even know how)
    so my question is:
    1. Why is this happening?
    2. How do I remove this and make objects use the regular material
    I'm asking for optimization preposes....
    Thanks!!

    Unity URP 2020.3.22
    Using mostly the "Baked Lit" shader

    upload_2022-7-11_13-12-38.png
     
  2. Neto_Kokku

    Neto_Kokku

    Joined:
    Feb 15, 2018
    Posts:
    1,751
    If you have code which access the renderer's .material property, Unity will create an instance (a copy) of the material and return that instead. It does that so that changes to the material of one renderer (like changing the color or texture) don't propagate to all others.

    If you want to access the material asset you have to use the .sharedMaterial property.
     
  3. Shanti-AnyVerse

    Shanti-AnyVerse

    Joined:
    Dec 26, 2021
    Posts:
    24
    hey and thanks!
    the problem is that this instance in still there after runtime (in editor) and sometimes more then once
    is it possible that a script is doing this?
    do you know a way to revert to the original material other then manually dragging each material to the object?
    this happened to hundreds of objects in my scene.
     
  4. bgolus

    bgolus

    Joined:
    Dec 7, 2012
    Posts:
    12,342
    Generally it's not possible for changes to game objects that occur during the play mode to stick around after leaving play mode. Unless you're using a tool that adds that functionality, or the change is being applied to the game objects before entering play mode.

    As @Neto_Kokku said, you have to search your code, and any assets you're using, for any uses of
    .material
    (or
    .materials
    ), and swap them for
    .sharedMaterial
    , or otherwise modify the code to make sure it only happens during play mode. And we do mean any use of it. Referencing
    .material
    for a log function will convert the material into an "instance" (which really just means it's a unique copy).