Search Unity

material.GetColor affects Draw Calls

Discussion in 'Editor & General Support' started by JoshOClock, Oct 8, 2013.

  1. JoshOClock

    JoshOClock

    Joined:
    Dec 8, 2010
    Posts:
    107
    I have a test scene with 6 models (all the same and same material) in my scene that are marked as static. When they render I get 1 draw call showing me that static batching is working.

    Now I've added some code to Awake():
    Code (csharp):
    1.  
    2.         m_RendererList = GetComponentsInChildren<MeshRenderer>();
    3.         m_DefaultColor = new Color[m_RendererList.Length];
    4.        
    5.         for (int i = 0; i < m_RendererList.Length; ++i)
    6.         {
    7.             MeshRenderer meshRen = m_RendererList[i];
    8.             //m_DefaultColor[i] = meshRen.material.GetColor("_Color");  // Problem Line
    9.         }
    10.  
    If I comment out one line, the static batching no longer works. I get 6 draw calls instead of 1.

    Anyone have any ideas on why that would be?
     
  2. Jessy

    Jessy

    Joined:
    Jun 7, 2007
    Posts:
    7,325
    You're not using sharedMaterial. Also, if it's in Awake, do you really need a for loop?

    Code (csharp):
    1. GetComponentsInChildren<MeshRenderer>().Select(renderer => renderer.sharedMaterial.color).ToArray();
     
  3. JoshOClock

    JoshOClock

    Joined:
    Dec 8, 2010
    Posts:
    107
    That was it. Thanks Jessy.

    One issue with using sharedMaterial is that I'm setting it later in the code and it's changing the material in the project. Which isn't a huge deal I guess.

    The main mechanic is that at certain points in the game certain static objects get brighter and others get darker. So I'll just use a different material for each grouping to solve the fact they all have the same 'sharedMaterial'.

    I usually avoid any LINQ code as I've read about overhead with memory allocations and then subsequent hitches during garbage collection. I could use it and then force garbage collection on Start or something, but if I avoid using them everywhere else, why be inconsistent. So.... I just never use them.
     
    Last edited: Oct 8, 2013
  4. shaderbytes

    shaderbytes

    Joined:
    Nov 11, 2010
    Posts:
    900
    To get around changes happening to the files in the editor just duplicate the sharedMaterial at runtime and assign it to the object. Then you can make edits at runtime to the sharedMaterial without affecting the original material. Once you exit play mode everything returns to normal ;)