Buttons not working in Unity

Description of the problem

A Canvas has been created with one or more buttons to perform an action, when running the game the buttons don’t work when you press them.

This is something that has happened to me on several occasions and can be due to several reasons.

Let’s assume you have a GameObject with the script with the button function defined as public, you have assigned it to the Button component of the Canvas and selected the appropriate function. If you haven’t done this and need help, I invite you to read this article on how to use Canvas buttons.

Possible Solution #1: No EventSystem in the hierarchy

When we create a Canvas, a GameObject called “EventSystem” is automatically created, as you can see in figure 1, this GameObject has some components associated to handle the input events (figure 2).

Fig. 1: GameObject EventSystem en la jerarquía.

Fig. 2: Componentes de EventSystem en el inspector.

If we accidentally delete the GameObject EventSystem, the mouse inputs are not detected and the Canvas buttons do not work.

To solve this we can create a second Canvas to make the EventSystem appear, then remove the second Canvas. Or we can simple create an EventSystem.

Possible Solution #2: Button configured as non-interactive

The Button component has a Boolean to disable it, as shown in figure 3 the “Interactable” box.

Fig. 3: The Interactable box is used to disable the button.

Possible Solution #3: Button is not a RayCast target

The button has an Image component for the background image and a Text component for the button text.

Both components have a box with the name “Raycast Target”, what it does is to enable the component to be detected by a ray tracing, the process by which it is detected that some element of the Canvas has been pressed.

In figures 3 and 4 we see the “Raycast Target” boxes. In a button if all the Raycast Target boxes are unchecked, it will not be possible to detect when clicking on those elements.

Fig. 4: Canvas image component.

Fig. 5: Canvas text component

To fix this problem, make sure that at least one Raycast Target box is enabled.

Leave a Comment

Your email address will not be published. Required fields are marked *