jon*_*max 5 c# unity-game-engine
我试图在我的游戏中为游戏对象设置材质,我在脚本中创建了该对象,因此我无法选择通过统一手动设置它。所有这些都必须在脚本等中。我的代码是
void Start()
{
GameObject cube2 = GameObject.CreatePrimitive(PrimitiveType.Cube);
cube2.transform.position = new Vector3(12f, -3f, -82.5f);
}
Run Code Online (Sandbox Code Playgroud)
所以我将我创建的立方体设置为“cube2”。所以又名我试图做的是将它设置为红色。我目前创建了一个名为 red 的材质。谢谢你。
首先,您必须获得材料的参考。您可以在组件上使用公共变量public Material yourMaterial;并在界面中使用拖放材质,也可以通过如下代码获取它:
// in the Start() method
Material yourMaterial = Resources.Load("red", typeof(Material)) as Material;
Run Code Online (Sandbox Code Playgroud)
然后,您可以使用以下字段将其分配给游戏对象renderer.material:
cube2.renderer.material = yourMaterial;
Run Code Online (Sandbox Code Playgroud)
注意:
我变老了…….renderer已经过时了,应该.GetComponent<Renderer>()像@Chopi 建议的那样使用。
编辑 :
为了Resources.Load工作,您的材料red.mat必须位于Resources文件夹中。如果它位于“Resources/materials/red.mat”等子文件夹中,那么这将导致:
Material yourMaterial = Resources.Load("materials/red", typeof(Material)) as Material;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7832 次 |
| 最近记录: |