如何在 Unity3D 中更改具有多个 material 的对象上的单个 material?

How to change a single material on an object with multiple materials in Unity3D?

请帮忙

#问题

我有一个 3d 模型有超过 1 个 material,我想通过 c# 更改 material 元素 2 查看图像“Material 元素顺序”enter image description here

这不起作用

  // Start is called before the first frame update
    public GameObject Cube;

    public Material Red;
    public Material Yellow;
    public Material ResultGreen;

    void Start()
    {
        Cube.gameObject.GetComponent<MeshRenderer>().materials[1] = ResultGreen;

    }

Renderer.materials is a property returns 或分配一个数组。

不能直接改变它的一个元素/它没有任何意义,因为你只交换数组中的元素returned 由 属性 然后扔掉那个数组。这实际上不会改变任何东西。

或者 Unity 如何表达它并实际告诉您确切的操作

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.

你更愿意像

那样做
// directly store the reference type you need most
public Renderer Cube;

private void Start()
{
    // get the current array of materials
    var materials = Cube.materials;
    // exchange one material
    materials[1] = ResultGreen; 
    // reassign the materials to the renderer
    Cube.materials = materials;
}