Two buttons are sharing the same script. So, How do i find which button was click and change the button color?
How do i use “this” here to access the clicked button to change its color?
Two buttons are sharing the same script. So, How do i find which button was click and change the button color?
How do i use “this” here to access the clicked button to change its color?
I use booleans to check if the button has been pressed, then textures in a custom style to switch the background color. Here’s some pseudo code.
bool buttonOn = false;
Texture2D ButtonOff; //one color texture
Texture2D ButtonOn; //another color texture
if (!buttonOn) {
if (GUI.Button (RECT), "button 1", GUI.skin.GetStyle("ButtonOff")) {
buttonOn = true;
DoTheButtonThing();
}
} else {
if (GUI.Button (RECT), "button 1", GUI.skin.GetStyle("ButtonOn")) {
buttonOn = false;
}
}
You could do the same thing by swapping the GUI content if you don’t want to mess with skins/styles.
I hope that helps.
You can do something like this. If I understand you correctly, you don’t need to worry about the same script being attached to multiple objects. When a button is clicked on, only it’s color will change, not all buttons with the script attached to it.
void Update () {
if (Input.GetMouseButtonDown(0)) {
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray, out hit)) {
if (hit.transform.gameObject == this.gameObject) {
GetComponent<Renderer>().material.color = Color.red;
//Or whatever other color operation you want to do...
}
}
}
}
You can have 2 bool var’s:
bool btn1;
bool btn2;
You can have 2 method’s:
public void onBtn1Click(){ btn1 = true; }
public void onBtn2Click(){ btn2 = true; }
And in
Update()
{
//check for true's and modify color
}