- Home /
How to make a field in inspector to pass events like "On Click()"?
Hi everyone!
I'm wondering how can I create a field to drag'n'drop functions in inspector like "On Click()" does. Anyone can help me with this?
Thanks!
Answer by DiegoSLTS · May 25, 2015 at 10:35 PM
Define a serializable class that extends UnityEvent and then add a member on your script of that type.
For example, an event that takes a string and a GameObject would look like this:
using UnityEngine;
using UnityEngine.Events;
using System;
using System.Collections;
[Serializable]
public class MyEvent : UnityEvent<string,GameObject> {}
public class EventTest : MonoBehaviour {
public MyEvent OnEvent;
}
The name of the member will be the name of the event in the inspector. To call all the functions added to that event use the Invoke method.
For an event that doesn't take any parameter define a class like this:
[Serializable]
public class MyEvent : UnityEvent {}
Also, look here: http://docs.unity3d.com/460/Documentation/Manual/UnityEvents.html
This was helpful, but a bit more clarification for those who come across this: I made SwipeEvents.cs, which looks like:
using UnityEngine;
using UnityEngine.Events;
using System;
using System.Collections;
[Serializable]
public class SwipeEvents : UnityEvent{ }
public class EventTest : $$anonymous$$onoBehaviour
{
public SwipeEvents OnEvent;
}
Then, on another script> "add a member on your script of that type": using System.Collections; using System.Collections.Generic; using UnityEngine;
public class SwipeListener : $$anonymous$$onoBehaviour {
private Vector3 fp; //First touch position
private Vector3 lp; //Last touch position
public float dragDistance; //$$anonymous$$imum distance for a swipe to be registered
public SwipeEvents OnLeft;
public SwipeEvents OnRight;
public SwipeEvents OnTap;
And finally, here's the part that took me a little bit to get right:
if ((lp.x > fp.x)) //If the movement was to the right)
{ //Right swipe
Debug.Log("Right Swipe");
OnRight.Invoke();
}
Works great, thanks again for the help!
Your answer
Follow this Question
Related Questions
Is there an event being fired off when the Inspector is being resized? 1 Answer
How to add UnityEvent using Custom Inspector? 1 Answer
Custom Inspector Invocation behaviour? 1 Answer
Left Click Up Event in Editor 4 Answers
Why cannot I drag and drop a gameObject from Hierarchy to a prefab's slot in the Inspector? 3 Answers