2

The latest versions of NGUI have this great tool that lets you pick which function within any of the target's scripts will be called when you click on it.

Basically, it's a select box within the inspector that gets automatically filled with all the functions from all the scripts attached to the game object.

How can I generate a function list that fills up automatically like this?

I don't want to have to maintain an enum with all the possible functions (including some that the current object might not have)

I tried looking at the code NGUI used, but it was a bit too complicated for me to understand right now.

Mauffler
  • 23
  • 1
  • 4
  • 1
    Well, what was the code that NGUI used, and why was it too complicated? Chances are that's the code you'll need to understand in order to create this functionality! – Dan Puzey Apr 02 '14 at 15:33
  • Some libraries use [`SendMessage`](http://docs.unity3d.com/Documentation/ScriptReference/GameObject.SendMessage.html), in which case you'll only need the name of the function and one optional argument. It works, but isn't high performance. It's possible NGUI is [using reflection to build a list of methods](http://stackoverflow.com/questions/5475209/get-class-methods-using-reflection). – rutter Apr 02 '14 at 21:35

1 Answers1

2

If you want to do it like in NGUI then use the tools that are available within NGUI itself and define a public variable like this:

public List<EventDelegate> DelegateList = new List<EventDelegate>();

With this, you can drop MonoBehaviour scripts in the Inspector field and can then select public methods/delegates contained in that script.

You can then invoke them like this:

void Start() {
  EventDelegate.Execute(DelegateList);
}

Now every method in your delegate list will be invoked. You can see this for example in the UIButton script where this is used to handle the OnClick delegates.

brasofilo
  • 25,496
  • 15
  • 91
  • 179
Patrick
  • 1,235
  • 1
  • 12
  • 15