how to change the material of an onclick object

Asked

Viewed 140 times

3

I am using unity3d, I have a Prefab of a sphere and another of a cube, with a simple material and I would like to know how I can change the material of these objects by clicking a button on UI.

1 answer

4

You need to reference their Renderer Material Component in your script... And as soon as they’re clicked, you switch this stuff to another one of your liking.

In Prefab you do something like this:

public class Prefab : MonoBehaviour
{
    private Material MaterialAtual;
    public Material NovoMaterial; //Lembre-se de arrastá-lo no inspector

    void Start()
    {
        //Pegue o material dentro de prefab.
        MaterialAtual = this.GetComponent<Renderer>().material
    }

    void TrocarMaterial()
    {
        // Troque o material
        MaterialAtual = NovoMaterial;
    }
}

On the Button you do something like this:

public class Prefab : MonoBehaviour
{
    public Prefab cubo;  //vincule-os pelo inspector, arrastando o gameobject aqui
    public Prefab esfera;

    void Start(){
        this.onClick.AddListener(() => BotaoClicado();
    }

    void BotaoClicado()
    {
        cubo.TrocarMaterial();
        esfera.TrocarMaterial();
    }
}

I hope this helps.

PS: references - Events of Buttons - https://docs.unity3d.com/ScriptReference/UI.Button-onClick.html

Material Renderer - https://docs.unity3d.com/ScriptReference/Renderer-material.html

PS-2: You can even change the color of your material without having to add another one if it’s not a complex texture, or something like that.. Just access the color value of the referenced material and change it, like this: MaterialAtual.color = cor-que-vc-quiser;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.