[ENG] Unity Button – Click via code, click effect (coloring) when hitting the button by code – like clicking it with mouse

csharpunity

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:

  1. How to activate a button by code (several ways)
  2. How to use the defined colors from a button when clicked

Let’s see what Unity got for us:

  1. How to activate a button by code – Straight forward without further explanation, here’s the code:

    All of these will do the same action: invoking by code the “onClick” Event.
  2. 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:

    1. Set the color when pressed – for example on a KeyDownEvent

    1. Set the color to normal again – for example on a KeyUpEvent

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!




1 Kommentar

  1. [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.

Antworten

Deine E-Mail-Adresse wird nicht veröffentlicht.


*


Diese Website verwendet Akismet, um Spam zu reduzieren. Erfahre mehr darüber, wie deine Kommentardaten verarbeitet werden.