How to make a button that changes a texture of an object?

Hey, I have a cube that when you press on it, it does something…
and I have a ball and I want to change his texture by pressing on the cube.
what do I need to write? I tried many scripts and they only changed the texture on the cube and not on the ball.
I use javascript but if you must use c# then use it.
Thanks :slight_smile:

(The 1,2,3,4 are the buttons or cubes that when they pressed they should change the texture of the ball).

Can you show the code?

Most likely you just need to add reference to the sphere:
var mySphere;

then assign the sphere into that at inspector,

then you can change the material for sphere:
mySphere.renderer.material.mainTexture = your_texture;

I would recommend switching between materials rather than textures.

You could attach a script similar to the following to each of your cube buttons:

using UnityEngine;

public class SkinSelectorButton : MonoBehaviour {

    // Reference to the sphere object.
    public GameObject sphere;
    // The material that is to be selected.
    public Material skinMaterial;

    private void OnMouseDown() {
        sphere.renderer.sharedMaterial = skinMaterial;
    }

}

Associate your sphere object with each button along with the material associated with each button.

I hope that this helps!

Bump

I did what you do and I assigned the ball and the material and when i click on the cube nothing happens…

Did you assign the variables in the inspector?

Yes:

You did put the script on the buttons right?
all 3 of them?
with different materials assigned to ‘SkinMaterial’?

I put the script only on one to test it out.

Do your cube buttons have colliders attached?

yes,

Can I just send you the scene and you can check whats wrong with it?

Please help me guys

Put the scripts on all 3 buttons.
Now put 3 DIFFERENT materials as SkinMaterial.

10000 thanks, great code, works perfect!!. I spend the whole day searching for the solution to this

I’m pretty lost here trying to follow what to do. I’m doing something similar, I have 1 object, and I want to be able to change between 2 different materials for that object to render. I have two buttons. I wrote a script called solidView, and a script called transparentView. In the inspector I’ve set solidView to a “Button1”, and transparentView to “Button2”. Inside the inspector I’ve set the same object for each button. What next?

Please share your code, using Code Tags.