- Home /
Script to respond to event chosen from Inspector
Hi all!
So I've just been working on this script, that I'd like to add to my NGUI UILabels, with an open field for a GameObject and the option to choose any event on the components of that GameObject to respond to. It's working, but I'd like to know what other think of it. Is this useful? Is there a better way?
Three scripts cover the system. 1) EventLabel.cs - this is added to the GameObject with a UILabel on it. 2) EventLabelEditor.cs - this is placed in an Editor folder 3) AnyScriptWithAnEvent.cs - this is added to the target GameObject in the inspector.
EventLabel.cs
public class EventLabel : MonoBehaviour
{
public GameObject target;
public Component eventScript;
public string eventName;
public int index = 0;
Delegate handler;
EventInfo eventInfo;
void Awake ()
{
eventInfo = eventScript.GetType ().GetEvent (eventName);
if (eventInfo != null) {
handler = Delegate.CreateDelegate (eventInfo.EventHandlerType, this, "Handler");
eventInfo.AddEventHandler (this, handler);
} else {
Debug.LogWarning ("EventInfo was not set! Events will not be captured by " + this.name);
}
}
void Handler (string myString)
{
print (myString);
}
}
EventLabelEditor.cs
public override void OnInspectorGUI ()
{
EventLabel evLabel = this.target as EventLabel;
evLabel.target = EditorGUILayout.ObjectField (evLabel.target, typeof(GameObject), true) as GameObject;
if (evLabel.target != null) {
List<KeyValuePair<Component, string>> optionsList = new List<KeyValuePair<Component, string>> ();
foreach (Component c in evLabel.target.GetComponents<Component>()) {
EventInfo[] events = c.GetType ().GetEvents ();
foreach (EventInfo e in events) {
optionsList.Add (new KeyValuePair<Component, string> (c, e.Name));
}
}
string[] options = new string[optionsList.Count];
for (int i = 0; i < optionsList.Count; i++) {
KeyValuePair<Component, string> method = optionsList [i];
options [i] = method.Key.ToString () + "." + method.Value;
}
if (evLabel.index >= options.Length) {
evLabel.index = 0;
}
evLabel.index = EditorGUILayout.Popup (evLabel.index, options);
if (options.Length != 0) {
evLabel.eventScript = optionsList [evLabel.index].Key;
evLabel.eventName = optionsList [evLabel.index].Value;
}
}
EditorUtility.SetDirty (evLabel);
}
}
This is what it shows in the inspector:
screenshot 2014-03-26 16.20.34.png
(24.1 kB)
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220613141252im_/https://answers.unity.com/themes/thub/images/avi.jpg)