总是会有一些奇奇怪怪的需求,总得根据这些奇奇怪怪的需求去实现对应的功能。 实现:获取某个物体所有子物体身上的材质球。
public static List<Material> FindChildMaterials(this Transform parent)
{
List<Material> t = new List<Material>();
Find<Material>(parent, ref t);
return t;
}
private static void Find<T>(Transform parent, ref List<Material> list) where T : Object
{
if (parent.GetComponent<MeshRenderer>())
{
Material[] m = parent.GetComponent<MeshRenderer>().materials;
if (m != null && m.Length > 0)
{
foreach (var item in m)
{
list.Add(item);
}
}
}
if (parent.GetComponent<SkinnedMeshRenderer>())
{
Material[] m = parent.GetComponent<SkinnedMeshRenderer>().materials;
if (m != null && m.Length > 0)
{
foreach (var item in m)
{
list.Add(item);
}
}
}
int number = parent.childCount;
while (number > 0)
{
for (int i = 0; i < parent.childCount; i++)
{
if (parent.GetChild(i).childCount > 0) Find<T>(parent.GetChild(i), ref list);
number--;
if (parent.GetChild(i).GetComponent<MeshRenderer>())
{
Material[] m = parent.GetChild(i).GetComponent<MeshRenderer>().materials;
if (m != null && m.Length > 0)
{
foreach (var item in m)
{
list.Add(item);
}
}
}
if (parent.GetChild(i).GetComponent<SkinnedMeshRenderer>())
{
Material[] m = parent.GetChild(i).GetComponent<SkinnedMeshRenderer>().materials;
if (m != null && m.Length > 0)
{
foreach (var item in m)
{
list.Add(item);
}
}
}
}
}
}
|