Get functions from a MonoScript

Good morning,
I’m working on an extension that calls a function with some specific parameters on it, but I can’t find a way to get a list of functions into a .cs script.

The idea is the same used in Unity UI Button, you attach a script to a MonoScript field and it should show a enum with the functions, where you can select one and it’ll be saved into a variable to use it later.

Anyone knows how this is done? I’ve seen lot of documentation and can’t find a solution.

Thanks everyone!

A function pointer in C# is either a System.Action or else a System.Func

Either can take arguments as templated types.

System.Action doit;  // for use with void funcName(void); functions
System.Action<int,string> doit; // for use with void funcName(int,string); functions
System.Func<int,string> doit; // for use with string funcName(int); functions

I always forget the order of that last one, so apologies if I got it reversed… :slight_smile:

You can store those as variables, or pass them into other functions as closures too. Look up functors for more info on the latter.

1 Like

Except those types don’t serialize and will be reset to null after deserialization, which will break the script. Deserialization will happen when you change anything in a script while scene is live. Same applies to C# delegates.


You can call any method on MonoBehavior (and its children) by its name using SendMessage function ( Unity - Scripting API: Component.SendMessage )

To have persistent callback that serializes and can be assigned through inspector, you need to use UnityEvent.

1 Like

If you want exactly what the UI Buttons are doing, simply put a public UnityEvent member in your script, as that’s what buttons use.

1 Like