domingo, 22 de mayo de 2016

Unity Events


Before proceeding with custom classes and practical applications in Unity, I wanted to show Unity Events, these are the events we see in the UI interface and we can use in our own scripts, although they are very useful and easy to use, for some reason they are not well documented, to learn them I had to analyze the source code of the UI. Let's proceed to make our own event:

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:


In this way, we can use these useful events that are very powerful and dynamic, they let us run other scripts methods visually, modify objects in the scene, etc. If we need to send a value with the event, such as the InputField which sends us a string each time the user updates the value or when he presses enter:


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>
{

}



In this simple way we can use these powerful and dynamic events in our games, any questions or suggestions leave it in the comments !.

No hay comentarios:

Publicar un comentario