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



请帮助

#问题我有一个3d模型,有多个材质,我想通过c#改变材质元素2查看图片"材料"元素"在这里输入图片描述

这个不能用

// 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属性返回或赋值一个数组。

不能直接改变它的一个元素/这是没有意义的,因为你只交换数组中的元素返回属性,然后丢弃该数组。这实际上不会改变什么。

或者Unity如何表达它并告诉你该怎么做

请注意,像Unity返回的所有数组一样,这返回一个副本的材料数组。如果您想要更改其中的一些材料,获取值,更改条目并设置材料.

你宁愿这样做

// 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;
}

相关内容

最新更新