[BUG] AddListener does not work

Using Unity version 5.5.2f1.

GameObject go = Instantiate(mapEntryObject, MapGrid, false);
Button button = go.GetComponent<Button>();
button.onClick.AddListener(DisableActivePanel);
Debug.Log("added the listener");

I am instantiating two objects at runtime (this is code in a for loop). After this I get the button and add the listener. The Debug.Log gets called, which means this code actually runs and no errors are encountered. However, when I look at the instantiated objects in the scene, the button does not have any OnClick() events added to it.

This is not a bug. The ones shown in the editor are persistent listeners(not added via script). If you want to add a persistent listener by script this can be done using the Editor api(wont work in a build). This is used for setting up event listeners so that they can be serialised in the scene, not for runtime use.
https://docs.unity3d.com/ScriptReference/Events.UnityEventTools.AddPersistentListener.html

Thank you! You’re correct that it works. Why doesn’t the persistent listener work in a build?

Persistent listeners are stored in the scene. They persist between scene reloads or play/stop a scene in the editor. You can’t make persistent changes to a scene in a build, so the option is Editor only. It would be nice to see the non persistent listeners for an event though, perhaps in the future.

And how we can click objects then ?

If anyone’s looking for a way to create persistent listeners from code, it’s worth checking this out:

1 Like

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class ConfirmationManager : MonoBehaviour
{
public Text confirmationText; // Assign in Inspector
public string yesButtonName;
public string noButtonName;

private string confirmationMessage;
private System.Action yesAction;
private System.Action noAction;

private Button yesButton;
private Button noButton;

private void Start()
{
yesButton = GameObject.Find(yesButtonName).GetComponent();
noButton = GameObject.Find(noButtonName).GetComponent();

yesButton.onClick.AddListener(Yes);
noButton.onClick.AddListener(No);

}

public void ShowConfirmation(string message, System.Action yes, System.Action no)
{
confirmationMessage = message;
yesAction = yes;
noAction = no;

confirmationText.text = message;
}

public void Yes()
{
yesAction?.Invoke();
HideConfirmation();
}

public void No()
{
noAction?.Invoke();
HideConfirmation();
}

private void HideConfirmation()
{
confirmationText.text = “”;
}
}
the addlistener event is error how to fix it