0
\$\begingroup\$

Based on this question on the Unity forum, I've made this code to instantiate a button and add an onClick event.

// Setting some other component properties right of the prefab.

shopTurretItem.GetComponent<UnityEngine.UI.Button>().onClick.AddListener(() => {
    UnityEngine.Debug.Log("Click");
});

Instantiate(shopTurretItem, transform);

The variabele shopTurretItem is my prefab type of UnityEngine.GameObject.

The problem is that the log Click will never be shown. If I add breakpoints on the first code line, the compiler will stop the code. If I place it into the closure, it'll never be hit if I click on that button.

This is the inspector of my prefab shopTurretItem.

What's wrong with this code?

\$\endgroup\$

4 Answers 4

1
\$\begingroup\$

Code-added events will never show in the inspector

This is not a problem. They're added at runtime, they work, and you can do so much more with them than you can in the inspector, so why do you care that they don't show up?

If the event isn't working, that's because you added the event to the prefab not its clone:

GameObject go = Instantiate(shopTurretItem, transform);
go.GetComponent<UnityEngine.UI.Button>().onClick.AddListener(() => {
    UnityEngine.Debug.Log("Click");
});

Note you can also simplify this by using imports:

GameObject go = Instantiate(shopTurretItem, transform);
go.GetComponent<Button>().onClick.AddListener(() => {
    Debug.Log("Click");
});
\$\endgroup\$
1
\$\begingroup\$

Also, since I have done this before, make sure that you have an event handler for your canvas. I had this issue once and discovered that it was all down to creating the canvas and UI buttons at runtime.

\$\endgroup\$
1
  • \$\begingroup\$ I've got an eventhandler but it's a +1 from me :) \$\endgroup\$ Sep 6, 2018 at 6:40
1
\$\begingroup\$

Judging by your code, isn't it that you are subscribing (adding a listener) to the Prefab's onClick event? why don't you add listener to the instantiated button?

UnityEngine.UI.Button newButton = Instantiate(shopTurretItem, transform) as UnityEngine.UI.Button;

newButton.onClick.AddListener(() => {
    UnityEngine.Debug.Log("Click");
});
\$\endgroup\$
0
\$\begingroup\$

I was having similar problems with unity ide v 2020. After much research I noticed render mode of all my canvas component were set to "Screen Space Camera". I switched the render mode to "Screen Space Overlay" and the click listener started working.

\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .