Name of button on click
I want to change the color of the button that I click on but I do not know the code (C #) button is pressed called? you can tell me, what button is pressed called in code? overall is: I want to write scripts and add to onclick () of the button has the effect : when I click on one button, that button will change color
I want to ask more one thing: I have to write something in this
Answer by btmedia14 · Jun 16, 2016 at 11:15 PM
Create a script for changing button colors, example code below. Then attach this script to a game object on your scene. It can be any game object, say the Main Camera object or even an empty game object. Now for each button that you want to change, you need to complete the OnClick() component section in the inspector for that button, as in your attached image.
In the OnClick() section: Either drag the game object with your attached script into the object field, or, click on the little circle with a dot beside the field and select the game object from the list that appears. Then select the name of the script itself.
Code example, the script is called MyButtonScript and contains the method ChangeButtonColor() that will be invoked by OnClick()
using UnityEngine;
using System.Collections;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class MyButtonScript : MonoBehaviour {
public void ChangeButtonColor()
{
// gets the button which was pressed
GameObject btnGameObject = EventSystem.current.currentSelectedGameObject;
ColorBlock btnColors = btnGameObject.GetComponent<Button>().colors;
btnColors.normalColor = Color.red; // Color of button when not selected
btnColors.pressedColor = Color.green; // Color when button is being pressed
btnColors.highlightedColor = Color.blue; // Color when button is focused or selected
//Now assign the updated colorBlock back to the button
btnGameObject.GetComponent<Button>().colors = btnColors;
}
}