using UnityEngine; using System.Collections; using UnityEngine.Events; public class TestUnityEvent : MonoBehaviour { public UnityEvent OnStart = new UnityEvent(); // Use this for initialization void Start () { OnStart.Invoke(); } // Update is called once per frame void Update () { } }
First, we add using UnityEngine.Events; at the top of our code, then we create a variable of type UnityEvent and give it a name, in this case my I'll name it "OnStart" because I will execute it in the method Start. Then, to call the event, we use the name of the event plus ". Invoke ()" so the event is executed, as you can see, it is very easy, when we add this script to a GameObject it looks like this:
To make this kind of event, we just need to create a class that inherits from UnityEvent and between the symbols '< >' we add the value we want to return, here the code example for string:
[System.Serializable] public class UnityEventString : UnityEngine.Events.UnityEvent<string> { }The class does not need to have anything special inside, just that inherits from UnityEngine.Events.UnityEvent and declare the types you want to return besides using the attribute System.Serializable as I explained in my previous post, it is used to let Unity display the custom class in the Unity inspector (actually, it does more than that, but in this case we use it for that). To use the event, you must declare a variable of your custom class type and invoke the method ".Invoke (StringValue)"
using UnityEngine; using System.Collections; using UnityEngine.Events; public class TestUnityEvent : MonoBehaviour { public UnityEvent OnStart = new UnityEvent(); public UnityEventString OnStart2 = new UnityEventString(); // Use this for initialization void Start () { OnStart.Invoke(); OnStart2.Invoke("Hola mundo"); } // Update is called once per frame void Update () { } } [System.Serializable] public class UnityEventString : UnityEngine.Events.UnityEvent<string> { }