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

时间:2016-10-08 08:09:50

标签: c# unity3d

我是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<Transform>();
        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<Renderer>();
        //   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个四边形。

1 个答案:

答案 0 :(得分:2)

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

trans.renderer.material = ....

应改为

trans.GetComponent<Renderer>().material = yourNewMaterial;

最后,在Unity中创建多维数据集或四元组时,MeshRenderer会自动附加到它们Renderer。因此,GetComponent<Renderer>()可能会出现运行时错误。请改用MeshRenderer

trans.GetComponent<MeshRenderer>().material = yourNewMaterial;

在运行时创建材料:

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

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

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<MeshRenderer>().material = myNewMaterial;
}