Press a button and change the texture of an object

I’m having some difficulties in creating a script to press a button to make me change the texture of an object…
if I could help !!
Thanks…

What you can do is make a script and add this:

public Material myMaterial;

void OnGUI() {
    if( GUI.Button( new Rect(0.0.100.40), "change texture" ) {
        gameObject.renderer.material.mainTexture = myMaterial;
    }
}

assign the Material you want it to change to in the inspector, or make it an array and let it pick the next texture in the array

Hope this helps :wink:

I’m still very green in this. I already have my object then I have to create a material and to associate this material on the subject? To press the button and change material (texture) …

Thank you!

have you attached the script to the gameObject you want the material to change of?

I think yes and I want a balcony for 3 buttons to change each of them a different texture to the balcony

If you want different buttons and each button representing 1 texture, you could do something like this:

public Texture[] textures;

void OnGUI() {
	if( GUI.Button( new Rect(0,0,50,20), "Change button" ) {
		renderer.material.mainTexture = textures[0];
	}

	if( GUI.Button( new Rect(0,0,50,20), "Change button" ) {
		renderer.material.mainTexture = textures[1];
	}

	if( GUI.Button( new Rect(0,0,50,20), "Change button" ) {
		renderer.material.mainTexture = textures[2];
	}
}

Else, you can use 1 button to choose a texture out of an array of textures:

public Texture[] textures;
private int count = 0;

void OnGUI() {
	if( GUI.Button( new Rect(0,0,50,20), "Change button" ) {
            count++;
        if( count > textures.Length) {
            count = 0;
        }
		renderer.material.mainTexture = textures[count];
	}
}

I created the script, I added the script to gameObject already have a material and the GameObject “BCE0043: Unexpected token: Material”
've rolled it all I do not know anything, you could not create a project to give it? already lost hours and hours and nothing;)

Thanks for your time :smile: