Home > Software design >  Unity Inspector to show a list of functions
Unity Inspector to show a list of functions

Time:02-05

I have an events manager with many events listed

public class EventsManager : MonoBehaviour
{
    public static EventsManager current;

    private void Awake()
    {
        current = this;
    }

    public event Action onStartSession;
    public void StartExperience() { onStartSession?.Invoke(); }

    public event Action onPauseSession;
    public void PauseExperience() { onPauseSession?.Invoke(); }

    public event Action onResumeSession;
    public void ResumeExperience() { onResumeSession?.Invoke(); }
}

Is it possible to have a dropdown in the inspector for another object where I can select a function from the Events Manager?

I tries something like this but it didn't work

 public class BtnController : MonoBehaviour
{
    private AssetBundle assetBundle;

    public Func<EventsManager> trigger;

    ...
}

I cannot see the list of the public functions when I select a button which has the BtnController.

I am using an Events Trigger component already so that wouldn't solve the problem.

CodePudding user response:

So in general the Unity Serializer only serializes types that are [Serializable] which neither Action nor Func (or in generaldelegate are.

There are for sure a couple of alternatives.

The simplest would be to use an enum like

public enum EventType
{
    Start,
    Pause,
    Resume,
    // ...
}

and then attach listeners like e.g.

public void ListenTo(EventType type, Action callback)
{
    switch(type)
    {
        case EventType.Start:
            onStartSession  = callback;
            break;
        case ....
    }
}

This EventType can now be exposed in the Inspector.

In general you should make those then

public event Action onStartSession;

so really only this class can invoke them.

  • Related