- Home /
How to change button image on click
I need to create a custom button with different images for different states of a button. For an example normal image will be changed in to another image after clicked. I have tried GUISkin but it doesn't allow me to change the position of many buttons. Please suggest a method.
Changing the position of buttons or change the images based on button state?
Answer by Lo0NuhtiK · Apr 03, 2014 at 07:47 AM
//example 1 variables
Rect buttonPosition = new Rect(5f, 5f, 50f, 50f) ;
//drag images onto slots in inspector
public Texture2D buttonOn, buttonOff ;
bool buttonIsOn = false ;
//example 2 variables
Rect buttonPositionOne = new Rect(55f, 5f, 50f, 50f) ;
Rect buttonPositionTwo = new Rect(5f, 55f, 50f, 50f) ;
bool buttonMoved = false ;
//example 3 variables (uses example 1 images [buttonOn] [buttonOff])
GUIContent content ;
Rect posOne = new Rect(105f, 5f, 50f, 50f), posTwo = new Rect(5f, 105f, 50f, 50f) ;
bool movedButton3 = false ;
void OnGUI()
{
//EX 1 : a button that changes image when pressed
if(GUI.Button(buttonPosition, buttonIsOn ? buttonOn : buttonOff))
buttonIsOn = !buttonIsOn ;
//EX 2 : a button that changes position when pressed
if(GUI.Button(buttonMoved ? buttonPositionTwo : buttonPositionOne, buttonMoved ? "evoM" : "Move"))
buttonMoved = !buttonMoved ;
//EX 3 : a button that changes position and content when pressed
content = movedButton3 ? new GUIContent("xD", buttonOn) : new GUIContent(":)", buttonOff) ;
if(GUI.Button(movedButton3 ? posTwo : posOne, content))
movedButton3 = !movedButton3 ;
}
Answer by Anwar_10 · Apr 03, 2014 at 08:43 AM
Hi.. Using the following code you can change image of button at same position and you want another button position then set coordinate of rectangle and first take two public Texture variable then pass this in GUI.Button.
bool FirstButton=false;
void OnGUI() { if(!FirstButton) { if(GUI.Button(new Rect(340, 720, 90,70),"First Button Image")) { FirstButton= true; } } if(FirstButton) { if(GUI.Button(new Rect(340, 720, 90,70),"Second Button Image")) { FirstButton= false; } } }
Your answer
Follow this Question
Related Questions
Click on box collider on an image in a canvas 0 Answers
Gui.Button Image in Button - error 1502 and 1503 0 Answers
How to access SourceImage component of a button in new GUI 4.6 1 Answer
Buttons become invisible when changing color (on Button or on Image) in script -1 Answers
Putting a delay in a button OnClick ? (Javascript) 3 Answers