Unity EventManager with delegate instead of UnityEvent

后端 未结 3 1961
小鲜肉
小鲜肉 2020-11-29 11:08

I am looking for c# delegate version of this Manager using UnityEvent. I don\'t want to use this because UnityEvent is slower than C# event at most time.

Any clue on

3条回答
  •  鱼传尺愫
    2020-11-29 11:15

    A little late to the party , @programmer answer at top really helped a lot , but still wanted to share an answer if some wants to trigger events with a return value , ofcourse moderators will know what to do with this answer.

    .net provides func and action , func or func

    here is @programmers code with return value :

     private Dictionary> eventDictionary;
    
    private static EventManager eventManager;
    
    public static EventManager instance
    {
        get
        {
            if (!eventManager)
            {
                eventManager = FindObjectOfType(typeof(EventManager)) as EventManager;
    
                if (!eventManager)
                {
                    Debug.LogError("There needs to be one active EventManger script on a GameObject in your scene.");
                }
                else
                {
                    eventManager.Init();
                }
            }
            return eventManager;
        }
    }
    
    void Init()
    {
        if (eventDictionary == null)
        {
            eventDictionary = new Dictionary>();
        }
    }
    
    public static void StartListening(string eventName,Func listener)
    {
        Func thisEvent;
        if (instance.eventDictionary.TryGetValue(eventName, out thisEvent))
        {
    
            thisEvent += listener;
    
    
            instance.eventDictionary[eventName] = thisEvent;
        }
        else
        {
    
            thisEvent += listener;
            instance.eventDictionary.Add(eventName, thisEvent);
        }
    }
    
    public static void StopListening(string eventName, Func listener)
    {
        if (eventManager == null) return;
        Func thisEvent;
        if (instance.eventDictionary.TryGetValue(eventName, out thisEvent))
        {
    
            thisEvent -= listener;
    
    
            instance.eventDictionary[eventName] = thisEvent;
        }
    }
    
    public static bool TriggerEvent(string eventName, EventParam eventParam)
    {
        Func thisEvent = null;
        if (instance.eventDictionary.TryGetValue(eventName, out thisEvent))
        {
            bool value;
            value = thisEvent.Invoke(eventParam);
            return value;
        }
        return false;
    }
    

    }

    public struct EventParam { public string param1;

    }

    So now Trigger can be called like this

    EventParam newparam = new EventParam();
        newparam.param1 = "Ty Mr Programmer this custom eventmanager";
        bool checkme;
        checkme =  EventManager.TriggerEvent("API", newparam);
    

提交回复
热议问题