Search Unity

  1. How can our website serve you better? Give us your feedback. Take our survey and let us know.
    Dismiss Notice

Renderer.GetMaterialCount()

Discussion in 'General Graphics' started by georgerh, Jun 12, 2021.

  1. georgerh

    georgerh

    Joined:
    Feb 28, 2020
    Posts:
    5
    I have a loop that sets per-material MaterialPropertyBlocks like this:

    Code (CSharp):
    1. for (int i = 0; i < materialCount; ++i)
    2. {
    3.     renderer.GetPropertyBlock(_propBlock, i);
    4.     _propBlock.SetFloat(_propertyId, propertyValue);
    5.     renderer.SetPropertyBlock(_propBlock, i);
    6. }
    7.  
    What's the correct way to get the material count?

    renderer.sharedMaterials.Length
    allocates memory for the array every time you call it.

    renderer.GetSharedMaterials(list)
    is slow because of the unnecessary copying and the list might have to reallocate memory as well.

    There is a
    Renderer.GetMaterialCount()
    method but it is private. You can call it via reflection but that allocates memory as well - presumably to auto-box the return value. Calling it via reflection is also much slower than renderer.sharedMaterials.Length.

    Did I miss something here?
     
unityunity