欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

unity3d:编辑器脚本,替换选中物体的材质

程序员文章站 2022-06-10 20:50:21
...
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
public class ChangeMat : MonoBehaviour {


    [MenuItem("Tools/ChangeNewMat")]
    static void ChangeNewMat()
    {
        GameObject obj = Selection.activeGameObject;
        foreach (Renderer it in obj.transform.GetComponentsInChildren<Renderer>())
        {
            Material mat = AssetDatabase.LoadAssetAtPath<Material>("Assets/ViveJx/Materials/JianXiuBall.mat");
            Material[] bufMat = new Material[it.sharedMaterials.Length];
            for (int i = 0; i < it.sharedMaterials.Length; i++)
            {
                bufMat[i] = mat;
            }
            it.sharedMaterials = bufMat;
        }
    }
}

Note that like all arrays returned by Unity, this returns a copy of materials array. If you want to change some materials in it, get the value, change an entry and set materials back.
要改变材质数组,得重新赋值一个数组