using System; using System.Collections.Generic; using UnityEngine; namespace Framework.Support { /// Contains helper methods for dealign with materials public static class MaterialHelper { /// Returns all materials used by the renderers of a game object /// Game object whose materials will be returned /// An array containing all materials used in a game object /// /// This will include all children with renderers /// public static Material[] GetMeshMaterials(GameObject actor) { Renderer[] renderers = actor.GetComponentsInChildren(); if((renderers == null) || (renderers.Length == 0)) { return new Material[0]; } var materialLists = new List(capacity: renderers.Length); int materialCount = 0; // Count the number of materials so we can avoid garbage production. // Under the assumption that querying a renderers materials involves // a Mono/Native boundary call, we remember the returned arrays instead // of asking for them multiple times. Maybe it's micro-optimization :) for(int index = 0; index < renderers.Length; ++index) { Material[] materialList = renderers[index].materials; if(materialList != null) { materialLists.Add(materialList); materialCount += materialList.Length; } } // Prepare the final material array for the caller var materials = new Material[materialCount]; int materialIndex = 0; for(int index = 0; index < materialLists.Count; ++index) { for(int listIndex = 0; listIndex < materialLists[index].Length; ++listIndex) { materials[materialIndex] = materialLists[index][listIndex]; ++materialIndex; } } return materials; } } } // namespace Framework.Support