In doc, what mean "Adding multiple identical listeners results in only a single call being made." ?

because when I add multiple identical listeners to an UnityEvent, it fire them all, not just one.

Maybe there’s a documentation error. Make a tiny project that proves it and submit a bug.

can you confirm I understood well the concept ?

using UnityEngine;
using UnityEngine.Events;


public class TestListener : MonoBehaviour
{
    public UnityEvent fire;


    void Fire()
    {
        Debug.Log("fire");  // fired 3 times. Doc says : Adding multiple identical listeners results in only a single call being made.
    }

    void OnEnable()
    {
        fire.AddListener(Fire);
        fire.AddListener(Fire);
        fire.AddListener(Fire);

        fire.Invoke();
    }

}

If it’s a documentation error, there’s a higher chance they change the actual behavior to match the docs than actually changing the docs.

1 Like

I am certainly not going to dig for that one magical piece of documentation you reference and yet don’t give me a link to!

https://docs.unity3d.com/ScriptReference/Events.UnityEvent.AddListener.html

If we understand “identical listeners,” well, it certainly calls them twice to me.

using UnityEngine;
using UnityEngine.UI;

public class gurg : MonoBehaviour
{
    public Button button;

    void Start()
    {
        button.onClick.AddListener(ButtonWasPressed);
        button.onClick.AddListener(ButtonWasPressed);
    }

    void ButtonWasPressed()
    {
        Debug.Log("Woo");
    }
}

6484000--728587--Screen Shot 2020-11-02 at 12.52.54 PM.png

filled report.

What was the bug report you filed pls? When did they address it? Still seeing it in 2022.3

Most likely this won’t get fixed. It USED to be that you had to wrap it in your own delegate:

btn.AddListener( delegate { MyFunc(); });

Now you can just do:

btn.AddListener( MyFunc);

and pass in a System.Action

Since it can now take a System.Action, I’m guessing their new overload simply wraps it in a brand-new fresh and shiny delegate{} and calls the original .AddListener()

This means that each time you call it, while you may give it the same System.Action, the overload wraps it in a different delegate{} made up on the spot in the function overload.

That means they are different delegates.

1 Like