- Home /
Unity editor inspector delegate / function pointer?
I would like to be able to add a public variable to my script that can accept a game object and then select a public function to execute. Basically, I want to do something exactly like this screenshot in my own custom script, but I'm not sure how to accomplish it:
Answer by zach-r-d · Aug 04, 2015 at 11:24 AM
This can be accomplished with UnityEvents. The usage is nice and simple too! There is a little bit of weirdness to deal with if the event takes parameters, though.
using UnityEngine;
using UnityEngine.Events;
public class ExecuteStuffOnClick : MonoBehaviour {
public UnityEvent myUnityEvent;
void Awake() {
if (myUnityEvent == null)
myUnityEvent = new UnityEvent();
}
public void OnMouseDown() {
myUnityEvent.Invoke();
}
}
This is exactly what I was looking for, thanks! If you have more than one function added to the inspector list, will myUnityEvent.Invoke() call all of them at once?
Yep! It's just like a C#/mono event, but with a nice inspector GUI. :)
Hey I know I'm a couple years late but thanks for this answer. Seems like a relatively simple/important thing to be able to do, and indeed it is very simple I just didn't know about it. Thanks again!
Yes, this way is good and simple, but it lets to serialize only methods with one, or without arguments. Did somebody know how to serialize methods with two or more args?
@Andrew_Zim : UnityEvent works with up to 4 arguments, see https://docs.unity3d.com/ScriptReference/Events.UnityEvent_4.html Beyond 4, you'll have to roll your own custom solution.
Answer by DerDicke · Aug 03, 2018 at 07:22 AM
This bugged me too. My solution is to use an interface. Implement your function using the interface, than in your 'sender' use GetComponent(); or like I did, make your Inspector field take a Monobehavior instead of a GameObj for even more control. In both cases you can write an custom Inspector and check if interface is present. If not, draw a messageBox and reject the dragged obj.
Has other advantages. You can communicate both ways (return values) and have more than one function.
Your answer

Follow this Question
Related Questions
Delegates in the Inspector 1 Answer
Drawing a custom variable in the inspector y position bugs selection 0 Answers
Draggable Nodes in Editor? 1 Answer
Make popup window in inspector if deleting GameObject 0 Answers
Drop down with sizes 1 Answer