首页 > 解决方案 > 更换材料的麻烦

问题描述

我正在编写我的第一个游戏,并且肯定会遇到 noobie 错误。能够通过其中的大多数工作,但这个让我很难过。

我有 4 种不同材质的皮肤可供选择,添加到一系列球中。我还计划在未来拥有更多。我拥有的代码适用于前两种材料,但是当我调用第 3 种或第 4 种材料时,它们只是默认为我的第二种材料。

以下代码位于 Start() 下的每个球上:

// Changes the material of the ball to a set type (set in the meshRenderer on each ball)
// [0] - plain, [1] - metallic, [2] - neon, [3] - pastel
MeshRenderer meshRenderer = gameObject.GetComponent<MeshRenderer>();
meshRenderer.material = meshRenderer.materials[0];

当它设置为材质[0]或[1]时,它可以正常工作,但是当它设置为[2]或[3]时,它默认为[1]材质。

材料设置在文件夹中:
* 资产/资源/材料/普通
* 资产/资源/材料/金属
* 资产/资源/材料/霓虹灯
* 资产/资源/材料/Pastel

命名约定的一个示例是 Black_plain 或 Blue_metallic。

我也将材质拖到了 MeshRenderer 材质数组中。

任何帮助或建议表示赞赏。正如我所说,我对此很陌生,并且很确定答案可能非常简单。>< 提前感谢您的帮助。

标签: c#unity3drenderer

解决方案


我终于找到了解决问题的办法。无论您从哪一个中删除 // 都会通过直接从文件夹中拉取材质而不是调用添加到 MeshRenderer 材质数组中的内容来将纹理更改为该材质。ballName 是球颜色的名称。

// Changes the material of the ball to a set type (set in the meshRenderer on each ball)
// [0] - plain, [1] - metallic, [2] - neon, [3] - pastel
MeshRenderer meshRenderer = gameObject.GetComponent<MeshRenderer>();

//meshRenderer.material = Resources.Load("Materials/Plain/" + ballName + "_plain", typeof(Material)) as Material;
//meshRenderer.material = Resources.Load("Materials/Metallic/" + ballName + "_metallic", typeof(Material)) as Material;
//meshRenderer.material = Resources.Load("Materials/Neon/" + ballName + "_neon", typeof(Material)) as Material;
meshRenderer.material = Resources.Load("Materials/Pastel/" + ballName + "_pastel", typeof(Material)) as Material;

希望这可以帮助遇到同样问题的其他人。


推荐阅读