Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice

[BUG] AddListener does not work

Discussion in 'Immediate Mode GUI (IMGUI)' started by Wattosan, May 30, 2017.

  1. Wattosan

    Wattosan

    Joined:
    Mar 22, 2013
    Posts:
    450
    Using Unity version 5.5.2f1.

    Code (CSharp):
    1. GameObject go = Instantiate(mapEntryObject, MapGrid, false);
    2. Button button = go.GetComponent<Button>();
    3. button.onClick.AddListener(DisableActivePanel);
    4. 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.
     
  2. karl_jones

    karl_jones

    Unity Technologies

    Joined:
    May 5, 2015
    Posts:
    7,850
    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
     
  3. Wattosan

    Wattosan

    Joined:
    Mar 22, 2013
    Posts:
    450
    Thank you! You're correct that it works. Why doesn't the persistent listener work in a build?
     
  4. karl_jones

    karl_jones

    Unity Technologies

    Joined:
    May 5, 2015
    Posts:
    7,850
    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.
     
  5. n7pankake

    n7pankake

    Joined:
    Nov 18, 2017
    Posts:
    18
    And how we can click objects then ?
     
  6. MaDDoX

    MaDDoX

    Joined:
    Nov 10, 2009
    Posts:
    764
    pmain8 likes this.