top of page
Search

Unity Events Vs Actions Vs Events

  • Writer: Faiq Laiq
    Faiq Laiq
  • Jun 20, 2020
  • 5 min read

Updated: Nov 17, 2020


In this article we are going to understand deeply on what are Unity Event, Actions, Events and when to use them. So fasten your seat belts and get ready for a bumpy ride.


Basic Intro:

You can skip basic intro if you already have an idea about these terms or you can read them in detail from following links.



Please note that examples given in this article are very simple and easily understandable. So if you’re having difficulty in learning these from their websites please see explanation bellow.


Unity Events

Most of our new developers doesn’t even know about unity events. It is a very simple way of allowing you to call any function or do any action directly from inspector once the code behind it is all setup.


1. Firstly add namespace to use unity events to a new script:

using UnityEngine.Events;

2. Create a variable of unity event:

public UnityEvent aNewEvent;

3. Now attach this newly created script to a component in Hierarchy. And you will be able to see an event in inspector where you can pass any function or action which will be called when ever you will invoke this event:

ree



4. You can invoke this event from anywhere by:

aNewEvent.Invoke();

5. Note that Unity events can only have up-to 1 variable of primitive type otherwise they will not be visible in inspector.


Actions

Actions are function delegates that are used when we want void as return type and can have any number of parameters.


1. Firstly add namespace to use Actions:

using System;

2. Now create a variable:

public Action action;

3. Also, you can have any number of parameters in it.

 public Action<int> action1;
 public Action<int, float> action2;
 public Action<string, int, float> action3;

4. Now you can assign function to these action(s):

 public Action<int> action;

 private void Start()
 {
    action = Function;
    action(10);
 }

 void Function(int value)
 {
    Debug.Log(value);
 }

Yes I know, why not call Function directly? We will answer this in Usage section.


Events

1. Create Variables

 public delegate void EconomyAction(int value);
 public static event EconomyAction economyUpdated;

2. Subscribe this event to get notification when it is called:

 private void OnEnable()
 {
     economyUpdated += UpdateEconomy;
 }

3. Always remember to unsubscribe after use:

 private void OnDisable()
 {
     economyUpdated -= UpdateEconomy;
 }

4. Update Economy is a function somewhere in same script or other.

 public void UpdateEconomy(int value)
 {
     Debug.Log("Updated economy: " + value);
 }

5. This function will be called when we call our event by:

 economyUpdated(10);

Where to use them?

After having basic idea of all three terms, now let’s see where to use them.


Unity Events

Unity events are used when you are writing some kind of plugin in which you will expose some key functions to other developers, so that they can perform their functionalities by just using your call backs from inspector, without having a need to understand your code.


Let’s take a scenario:

1. You are asked to integrate Facebook SDK in a unity game.

2. Another developer is already working on UI of this game.

3. You want to show some connection success/failure messages on UI.

4. What should you do? Create your own UI to display them? Ask that developer to help?

5. No, just expose some unity events like OnComplete and OnFailure. That UI developer will simply call his/her functionality from inspector using these events.


Actions

There are hundreds of scenarios where we call a function to start a process then need callback on its completion. To fill up this need Actions comes into action :-D.


Let’s take a scenario here as well to clear things up:

1. Imagine you’re calling a function to get some data from online server (APIs).

2. On response from server you want to perform a functionality to manipulate that data.

3. Simply send your function in parameter list, and call it when you receive response.


Consider following class

public class FacebookSDK : MonoBehaviour
{
    public UnityEvent OnSuccess;
    public UnityEvent OnFailure;

    public class Data
    {
       public int ID;
       public string name;
       public string otherInformations;
    }

    public void AFunction()
    {
       Example.instance.GetData(Response);
    }

    public void Response(Data data)
    {
       // This function will be called after task completion
       // Manipulate your data here
    }
}

AFunction is calling GetData from Example class and sending Response function in parameter list which will be called when we recieve data from the server. Let’s also see what’s in example class.

public class Example : MonoBehaviour
{
    public static Example instance;

    private void Awake()
    {
       instance = this;
    }

    public void GetData(Action<FacebookSDK.Data> callback)
    {
       // Call API and send data back
       StartCoroutine(GetDataE(callback));
    }

    IEnumerator GetDataE(Action<FacebookSDK.Data> callback)
    {
       yield return new WaitForSeconds(1);
       callback(new FacebookSDK.Data{ID = 0, name = "A Name"});
    }
}

I am using simply wait for seconds, because I am not implementing API call procedure in which it is replaced by the time server is taking to process your request and send back response (we will cover that in another article). Though, after that time callback is called which will automatically call Response in FacebookSDK class.


Events

Events are very useful when you want to notify a change on multiple functions without one by one calling the list of all. Let’s take an example.

For instance:

1. You can have multiple screens in your game, like

  • Game-play

  • Main menu

  • Shop etc.

2. And, there is a currency in your game called coins.

3. You collect coins from game-play or purchase them from shop.

4. They are displayed in all of the three screen.

5. Now, when you purchase some coins from shop menu, you want them to get updated automatically on game-play and main menu as well.

6. So, simply call an event when you purchase something and subscribe it from all three menus.

7. In this way calling a single function OnPurchase will update values every where. Let’s see the code of these three menus and menu manager.


Menu Manager:

public class MenuManager : MonoBehaviour
{
    public static MenuManager Instance;

    private void Awake()
    {
       Instance = this;
    }

    public int totalCoins;

    public delegate void CoinsAction(int value);
    public static event CoinsAction CoinsUpdated;

    public void UpdateCoins(int value)
    {
       if (CoinsUpdated != null)
       CoinsUpdated(value);
    }
}

Shop Menu:

public class ShopMenuEventListener : MonoBehaviour
{
    public Text coins;

    private void OnEnable()
    {
    MenuManager.CoinsUpdated += UpdateScore;
    }

    private void OnDisable()
    {
       MenuManager.CoinsUpdated -= UpdateScore;
    }

    public void UpdateScore(int value)
    {
       coins.text = value.ToString();
    }

    public void OnPurchaseSuccessful(int value)
    {
       MenuManager.Instance.totalCoins += value;
       MenuManager.Instance.UpdateCoins(value);
    }
}

Main Menu:

public class ManiMenuEventListener : MonoBehaviour
{
    public Text coins;

    private void OnEnable()
    {
       MenuManager.CoinsUpdated += UpdateScore;
    }

    private void OnDisable()
    {
       MenuManager.CoinsUpdated -= UpdateScore;
    }

    public void UpdateScore(int value)
    {
       coins.text = value.ToString();
    }
}

Gameplay Menu:

public class GameplayEventListener : MonoBehaviour
{
    public Text coins;

    private void OnEnable()
    {
       MenuManager.CoinsUpdated += UpdateScore;
    }

    private void OnDisable()
    {
       MenuManager.CoinsUpdated -= UpdateScore;
    }

    public void UpdateScore(int value)
    {
       coins.text = value.ToString();
    }
}

As you can see in above scripts, updating values on runtime becomes very easy by using simple events. Thanks for reading, this articles is always open for any feedback or suggestion.

 
 
 

Comments


Post: Blog2_Post

03054044344

©2020 by Faiq Laiq. Proudly created with Wix.com

bottom of page