Skip to content
The Chat Archive
gpt-3.5-turbo-0613· OpenAI WildChat-4.8M (AI2)

how c# check duplicate unity event Action listeners

  1. User

    how c# check duplicate unity event Action listeners

  2. Assistant

    In C#, you can check whether an Action listener is already registered using the Delegate.Equals() method. Here's an example:

    using UnityEngine;
    using System;
    
    public class EventManager : MonoBehaviour
    {
        // Define the event using Action delegate
        public event Action MyEvent;
    
        // Subscribe a listener to the event
        public void SubscribeListener(Action listener)
        {
            if (!IsListenerRegistered(listener)) // Check if listener is already registered
            {
                MyEvent += listener;
            }
        }
    
        // Unsubscribe a listener from the event
        public void UnsubscribeListener(Action listener)
        {
            if (IsListenerRegistered(listener)) // Check if listener is registered
            {
                MyEvent -= listener;
            }
        }
    
        // Check if a listener is already registered
        private bool IsListenerRegistered(Action listener)
        {
            if (MyEvent == null)
            {
                return false;
            }
    
            // Get the invocation list of the event
            Delegate[] invocationList = MyEvent.GetInvocationList();
    
            // Check each delegate in the invocation list
            foreach (Delegate del in invocationList)
            {
                // Check if the current delegate is equal to the given listener
                if (del.Equals(listener))
                {
                    return true;
                }
            }
    
            return false;
        }
    
        // Usage example
        private void Start()
        {
            Action listener1 = () => Debug.Log("Listener 1 invoked");
            Action listener2 = () => Debug.Log("Listener 2 invoked");
    
            SubscribeListener(listener1);
            SubscribeListener(listener2);
            SubscribeListener(listener1); // This will not add the duplicate listener
    
            MyEvent?.Invoke();
    
            UnsubscribeListener(listener2);
    
            MyEvent?.Invoke();
        }
    }
    

    In this example, the SubscribeListener method checks whether the provided listener is already registered using the IsListenerRegistered method. The IsListenerRegistered method compares each delegate in the event's invocation list with the given listener using the Delegate.Equals() method.

    Please note that this approach assumes that the event is a simple event using the Action delegate. If you are using a custom delegate or multi-cast delegate, you may need to adjust the code accordingly.