我如何使用编辑器脚本销毁一个游戏对象的材料并添加一个新的材料?

问题描述 投票:0回答:1
var newmat = AssetDatabase.LoadAssetAtPath("Assets/Materials/Univeral Render Pipeline Lit.mat", typeof(Material));

        var allgameobjects = FindObjectsOfType<GameObject>();

        foreach(GameObject go in allgameobjects)
        {
            if (go.GetComponent<Renderer>() != null)
            {
                if (go.GetComponent<Renderer>().sharedMaterial.name.StartsWith("Default"))
                {
                    DestroyImmediate(go.GetComponent<Renderer>().sharedMaterial);

                    // Add here the newmat material to the gameobject
                }
            }
        }

这将销毁从游戏对象删除当前材料,我怎么能添加一个新的材料呢?我想添加新的材质。

也许没有必要销毁只是为了切换材料?

c# unity3d
1个回答
1
投票
var newmat = AssetDatabase.LoadAssetAtPath("Assets/Materials/Univeral Render Pipeline Lit.mat", typeof(Material));

        var allgameobjects = FindObjectsOfType<GameObject>();

        foreach(GameObject go in allgameobjects)
        {
            if (go.GetComponent<Renderer>() != null)
            {
                if (go.GetComponent<Renderer>().sharedMaterial.name.StartsWith("Default"))
                {
                    DestroyImmediate(go.GetComponent<Renderer>().sharedMaterial);

                    //Add material
                    go.GetComponent<Renderer>().sharedMaterial = newmat;
                }
            }
        }

但我认为你也可以直接改变材料

var newmat = AssetDatabase.LoadAssetAtPath("Assets/Materials/Univeral Render Pipeline Lit.mat", typeof(Material));

        var allgameobjects = FindObjectsOfType<GameObject>();

        foreach(GameObject go in allgameobjects)
        {
            if (go.GetComponent<Renderer>() != null)
            {
                if (go.GetComponent<Renderer>().sharedMaterial.name.StartsWith("Default"))
                {
                    go.GetComponent<Renderer>().sharedMaterial = newmat;
                }
            }
        }

对于地形,它是 terrain.materialTemplate

© www.soinside.com 2019 - 2024. All rights reserved.