简体   繁体   中英

Change Material Image/Texture from Sphere with Script

我正在尝试使用代码从Material的Sphere更改Image / Texture。

Try this in a new script and add it to your Object as a Component:

C#:

class MaterialSetter : MonoBehaviour{
    public void SetMaterial(Material newMaterial)
    {
        Renderer renderer = GetComponent<Renderer>();
        renderer.material = newMaterial;
    }
}

You can call SetMaterial from any other script, provided you have the reference to your target object. You could, for example, set the material at the beginning of your game adding a Start() function to your MaterialSetter class:

C#:

class MaterialSetter : MonoBehaviour{
    public Material StartMaterial;

    // ...
    void Start()
    {
        SetMaterial(StartMaterial);
    }
}

Now if you want to set the Material by name, your Material needs to be in the folder Assets/Resources. Everything you get via Resources.Load, must be located in that folder. Then the code would look like this:

C#:

class MaterialSetter : MonoBehaviour{
    public void SetMaterial(string materialName)
    {
        Material mat = Resources.Load(materialName, typeof(Material)) as Material;
        Renderer renderer = GetComponent<Renderer>();
        renderer.material = newMaterial;
    }
}

If you want to change the texture used in your material (assuming you use the Unity Standard Shader) you'll have to get a texture by reference or from your resources, if you want to get it by name:

C#:

public void SetTexture(string textureName)
{
    Texture tex = Resources.Load(textureName, typeof(Texture)) as Texture;
    Renderer renderer = GetComponent<Renderer>();
    renderer.material.SetTexture("_MainTex", tex);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM