batteryDiagnosis/Assets/Scripts/ChangeObjMat.cs

85 lines
2.2 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

using System.Collections;
using System.Collections.Generic;
using System.Linq;
using UnityEngine;
public class ChangeObjMat : MonoBehaviour
{
//透明材质(想要替换的材质)
public Material m_TM;
/// <summary>
/// 保存所有的MeshRenderer
/// </summary>
public List<MeshRenderer> m_RendererList;
/// <summary>
/// 保存子物体下 每个子物体的所有材质(为了还原初始物体上的材质)
/// </summary>
private List<List<Material>> m_RecordRendererList = new List<List<Material>>();
void Start()
{
//所有子物体的MeshRenderer
m_RendererList = GetComponentsInChildren<MeshRenderer>().ToList();
//保存所有子物体所有材质
m_RecordRendererList.Clear();
for (int i = 0; i < m_RendererList.Count; i++)
{
m_RecordRendererList.Add(m_RendererList[i].materials.ToList());
}
ChangeChildrenMat(isGo);
}
/// <summary>
/// 改变子物体材质
/// </summary>
/// <param name="Change"></param>
public void ChangeChildrenMat(bool Change)
{
if (Change)
{//替换所有的子物体材质为 m_TM
for (int i = 0; i < m_RendererList.Count; i++)
{
int len = m_RendererList[i].materials.Length;
//创建相同大小的的数据保存材质m_TM
Material[] matArr = new Material[len];
for (int j = 0; j < len; j++)
{
matArr[j] = m_TM;
}
//赋值
for (int j = 0; j < len; j++)
{
m_RendererList[i].materials = matArr;//整个数组赋值不能m_RendererList[i].materials[j] = matarr赋值具体原因不甚了解
}
}
}
else
{//还原所有物体材质
for (int i = 0; i < m_RecordRendererList.Count; i++)
{
List<Material> materialList = m_RecordRendererList[i];
m_RendererList[i].materials = materialList.ToArray();
}
}
}
//测试使用
public bool isGo = true;
void Update()
{
if (Input.GetKeyDown(KeyCode.A))
{
ChangeChildrenMat(isGo);
isGo = !isGo;
}
}
}