
Hello Unity developers,
as you know, you’ll come sometime to the point that you want to create a button which can be activated by a keyboard or joypad button. While crawling the internet, i’ve seen a lot of code which just sends the “OnClick” Event to that button but won’t color it.
This is why I post this little guide/hint, you’ll find following topics:
- How to activate a button by code (several ways)
- How to use the defined colors from a button when clicked
Let’s see what Unity got for us:
- How to activate a button by code – Straight forward without further explanation, here’s the code:
123456789// Execute Events// GameObject myButton;// myButton should be bound the a button...// 1. using execute eventsExecuteEvents.Execute<IPointerClickHandler>(myButton, new PointerEventData(EventSystem.current), ExecuteEvents.pointerClickHandler);// 2. using OnPointerClickmyButton.GetComponent<Button>().OnPointerClick(new PointerEventData(EventSystem.current));// 3. Using onClick.Invoke()myButton.GetComponent<Button>().onClick.Invoke();
All of these will do the same action: invoking by code the “onClick” Event. - How to use the defined colors from a button when clicked
When activating a button by code you may notice that the button won’t recolor – it just looks like the button has not been clicked. The solution simple, just look at this code listening:
- Set the color when pressed – for example on a KeyDownEvent
1 |
myButton.GetComponent<Image>().color = myButton.GetComponent<Button>().colors.pressedColor; |
- Set the color to normal again – for example on a KeyUpEvent
1 |
myButton.GetComponent<Image>().color = myButton.GetComponent<Button>().colors.normalColor; |
The property colors in the Button class is from the type ColorBlock (link to ScriptReference). There are some other colors, just have a look at the Unity Scripting reference.
For an implementation you could have a look at my code at the Asset Store. Link will follow.
Thanks for reading and have fun!
[ENG] Unity Button – Click via code, click effect (coloring) when hitting the button by code – like clicking it with mouse
the above post is a good tutorial and helps lots for my current projects. Thanks for making.