unity批量获取物体组件修改值,拓展子物体查询

using UnityEngine;
using System.Collections;

public class Game : MonoBehaviour {
    // Use this for initialization
    void Start () {
        FindMaterials(this.transform);
       
    }
    // 根据 物体名称 获取 物体下的任何地方的子物体
    void FindChild(Transform go,string name,ref Transform tr)
    {
        
        if(go.name.Equals(name))
        {
            tr = go.transform;
            return;
        }
        if(go.childCount>0)
        {
            for(int i=0;i<go.childCount;i++)
            {
                if(go.GetChild(i).childCount>0)
                {
                    FindChild(go.GetChild(i), name, ref tr);
                }
                if(go.GetChild(i).name.Equals(name))
                {
                    tr = go.GetChild(i).transform;
                }
            }
        }
    }
//批量修改 但是只是引用 运行时起作用
void FindMaterials(Transform go) { MeshRenderer temp; if(go!=null&& go.childCount>0) { for(int i =0 ;i<go.childCount;i++) { //temps 第一级子物体 Transform temps = go.GetChild(i); if (temps.childCount > 0) FindMaterials(temps); //获取这一级子物体的 Material 更改 temp = temps.GetComponent<MeshRenderer>(); if (temp == null) { continue; }else { Shader s = Shader.Find("Custom/Mask"); if (temp.material.shader !=s) temp.material.shader = s; } } } } }
原文地址:https://www.cnblogs.com/bambomtan/p/4739926.html