Search Unity

Dynamically changing material, but sharing it among GameObjects

Discussion in 'Scripting' started by kleinfb, Oct 28, 2014.

  1. kleinfb

    kleinfb

    Joined:
    Sep 21, 2012
    Posts:
    96
    Hey guys... question is simple...

    I have 100 different visual GameObjects (let us say blue cubes) which have the exact same mesh... they all share de same material, lots of draw calls saved. Now, I want to change the material in 4 of them (to change their color, since changing the color of a shared material would affect all other materials...), in runtime. But I would like to keep sparing draw calls... the deal is that I well... I am not being able to achieve it.

    Anyone knows the steps to achieve that sort of behaviour? If more info about my case is needed, I will gladly provide, but I do not think it is...

    Code (CSharp):
    1. gameObject.renderer.material.color = cellSelectedColor;
    This is what I am trying for now... I am changing the color, and I believe that it dynamically creates a new material for each gameObject..

    Thanks in advance...
     
  2. DoomSamurai

    DoomSamurai

    Joined:
    Oct 10, 2012
    Posts:
    159
    Do not ever use the "material" property, even just to check the content of the variable. Instead, use "sharedMaterial".

    Also, I think you cannot directly set it's color, it probably creates a separate instance. You need to create an instance of a material at runtime and make sure all the objects that you want to share this matertial use this specific instance. Maybe with a static Material variable or something.
     
    kleinfb likes this.
  3. DoomSamurai

    DoomSamurai

    Joined:
    Oct 10, 2012
    Posts:
    159
  4. kleinfb

    kleinfb

    Joined:
    Sep 21, 2012
    Posts:
    96
    @DoomSamurai thanks for the info!
    I will try the runtime material creation, and I will report back (Y)

    You got me curious though... what is the reason for never using "material" property?

    Thanks, a bunch!
     
  5. DoomSamurai

    DoomSamurai

    Joined:
    Oct 10, 2012
    Posts:
    159
    If you access the material property, even if it's just a getter, it creates an instance material for your mesh and replaces the sharedMaterial. This cause Dynamic Batching to break. I don't know why that is so, I guess Unity internally creates a material when the "material' property is accessed for the first time. I ran into this problem for my hexagon grid!
     
    kleinfb likes this.
  6. kleinfb

    kleinfb

    Joined:
    Sep 21, 2012
    Posts:
    96
    Thanks a bunch again fellow (Y)