# AddListener will not listen to onClick event

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.

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?

# 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);
UnityEngine.Debug.Log("Click");
});


Note you can also simplify this by using imports:

GameObject go = Instantiate(shopTurretItem, transform);
Debug.Log("Click");
});


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.

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

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;