Change Texture on Button press

Hi, I have 2 textures and I want to change the texture of an object by pressing a specific button. If I press the same button again the texture switches back to the previous one and so on.

My current code is:

var color1 : Texture;
var color2 : Texture;
var CurrentColor : boolean = true;

function Update () {

// switch colors

if(Input.GetButtonDown(“Jump”) && CurrentColor != false) {

renderer.material.mainTexture = color2;
CurrentColor = false;
}

else 
renderer.material.mainTexture = color1;
CurrentColor = true;

}

My Problem now is that my object has Colour1 but if I press space Colour2 appears for just a blink of a secon and switches directly to Color1 again.

1 Answer

1

that's because it changes every time you're not pressing space, thanks to the else statement. You should do something like this

    if(Input.GetButtonDown("Jump"))
    {
        if(renderer.material.mainTexture == color1)
           renderer.material.mainTexture = color2;
        else
           renderer.material.mainTexture = color1;
    }

you can also add this boolean if you need it for anything else. This way, whenever you press space, it checks the current color and changes it to the other one