从代码创建材料并将其分配给对象

我是Unity3d的新手,我有一个包含6个四边形的预制件,使它成为一个立方体。我想将图像纹理添加到立方体的不同面上。 我从webservice获取图像所以,我必须在脚本中添加或更改材料。 我面临的问题是,我无法在gameObject中找到材料属性。

我试过下面的代码:

using UnityEngine; using System.Collections; public class shelfRuntime : MonoBehaviour { public GameObject bottle; public GameObject newBottle; // Use this for initialization void Start () { iterateChildren(newBottle.transform.root); GameObject rocketClone = (GameObject)Instantiate(bottle, bottle.transform.position, bottle.transform.rotation); rocketClone.transform.localScale += new Vector3(1, 1, 1); GameObject newBottleInMaking = (GameObject)Instantiate(newBottle, newBottle.transform.position, newBottle.transform.rotation); Transform[] allChildren = newBottleInMaking.GetComponentsInChildren(); foreach (Transform child in allChildren) { // do whatever with child transform here } } void iterateChildren(Transform trans) { Debug.Log(trans.name); if (trans.name == "Back") { var ting = trans.gameObject.GetComponent(); // trans.renderer.material // there is no material property here } // Do whatever logic you want on child objects here if (trans.childCount == 0) return; foreach (Transform tran in trans) { iterateChildren(tran); } } // Update is called once per frame void Update () { } } 

如何将材料设置为四边形? 我的预制件内有6个四边形。

您无法再直接在Unity中访问某些组件。 您必须使用GetComponent来获取组件( Renderer ),然后从中访问该材料。

 trans.renderer.material = .... 

应该改为

 trans.GetComponent().material = yourNewMaterial; 

最后,当在Unity中创建Cube或Quad时, MeshRenderer会自动附加到它们而不是Renderer 。 因此, GetComponent()可能会出现运行时错误。 请改用MeshRenderer

 trans.GetComponent().material = yourNewMaterial; 

在运行时创建材料:

 Material myNewMaterial = new Material(Shader.Find("Standard")); 

下面的示例将创建一个Material,为其指定标准着色器,然后在将myTexture变量应用于myTexture之前将纹理更改为纹理。

 public Texture myTexture; void Start() { //Find the Standard Shader Material myNewMaterial = new Material(Shader.Find("Standard")); //Set Texture on the material myNewMaterial.SetTexture("_MainTex", myTexture); //Apply to GameObject trans.GetComponent().material = myNewMaterial; }