Creating Events dynamicaly

Hello. I am using following code to create UnityEvents dynamicaly by enum collection.

/// <summary>
    /// All no parameters events
    /// </summary>
    public enum NoParamEvents
    {
        AttackUp,
        AttackDn,
        AttackLt,
        AttackRt,
    }
/// <summary>
    /// Dictionary for events with no params related to NoParamEvents enum
    /// </summary>
    public Dictionary<NoParamEvents, UnityEvent> _events = new Dictionary<NoParamEvents, UnityEvent>();
   /// <summary>
    /// Adds events into dictionary. Key is enum variables
    /// </summary>
    private void FillUpDictionaryNoPatamEvents()
    {
        foreach (var e in (NoParamEvents.GetValues(typeof(NoParamEvents))))
        {
            _events.Add((NoParamEvents)e, new UnityEvent());
        }
    }

now I want ot use event instead of UnityEvent
[/code]

public delegate void theDelegate();
public Dictionary<NoParamEvents, theDelegate> _es = new Dictionary<NoParamEvents, theDelegate>();
private void FillUpDictionaryNoPatamEvents()
    {
        foreach (var e in (NoParamEvents.GetValues(typeof(NoParamEvents))))
        {
            _es.Add((NoParamEvents)e, new theDelegate);
        }
    }

I stack on error for new theDelegate.
_es.Add((NoParamEvents)e,new theDelegate);

How to handle the error?

Don’t you mean,

_es.Add((NoParamEvents)e,new theDelegate() );

THank you for fast reply, but it not fixes the error.
The error message is “theDelegate doesnt contain a constructor that takes 0 arguments”

when I create
public theDelegate someEvent;
there some value already setted by the system.
what type of value do i need to put for non pablic theDelegate field?

I think I figured out the syntax:

        foreach (var e in (NoParamEvents.GetValues(typeof(NoParamEvents))))
        {
            _es.Add((NoParamEvents)e, () => { });
        }

// add a listener
        _es[NoParamEvents.AttackDn] += () => { Debug.Log("YUP!"); };

// test invoke
        _es[NoParamEvents.AttackDn].Invoke();

Line 3 above just adds an empty blank lambda function, you can piggyback on as many other callbacks as you want, as with any delegate/callback.

5902733--629996--Screen Shot 2020-05-26 at 3.16.16 PM.png

1 Like

Thank you very much!

1 Like