THIS CONTENT DOWNLOAD SHORTLY

Objective

The main objective of this blog post is to give you an idea about how to use C# UnityEvents in Unity.

 

What is UnityEvent?

How to use UnityEvents?

How it is differ from C# Event (Event Delegate)?

Which one is better to use C# Event or UnityEvent?

Let’s dive into UnityEvent...

As per Unity API documentation,

  • UnityEvents are a way of allowing user driven callback to be persisted from edit time to run time without the need for additional programming and script configuration.
  • UnityEvents can be added to any MonoBehaviour and are executed from code like a standard .net Event Delegate.
  • When a UnityEvent is added to a MonoBehaviour it appears in the Inspector and persistent callbacks can be added.

Let’s take an example,

Step 1

  • Create a canvas with text field.

Step 2

  • Create Empty gameObject name it as you like.

Step 3

  • Create C# script name it as you like.

Write following code in UnityEventDemo.cs.

public class UnityEventDemo : MonoBehaviour {

	#region PUBLIC_VERIABLE
	public Text demoText;
	#endregion

	#region PRIVATE_VARIABLE
	int initialSize=10;
	int maxSize=100 ;
	#endregion

	#region UNITY_CALLBACKS
	void start(){
	}
	#endregion

	#region PUBLIC_VARIABLE
	public void TextChange(){
		StartCoroutine (WaitAndChangeText (1));
	}
	#endregion

	#region CO_ROUTINE
	IEnumerator WaitAndChangeText(float time){
		float i = 0;
		float rate = 1 / time;
		while (i < 1) {
			i += Time.deltaTime * rate;
			demoText.resizeTextMaxSize = (int)Mathf.Lerp (initialSize, maxSize, i);
			yield return new WaitForSeconds (0.01f);
		}
	}
	#endregion

}

Step 4

  • Assign it to the Empty gameObject (created in step 2).
  • This script has only one method which is TextChange(), used for resize the text.

Now you may think what about UnityEvent..?

How UnityEvent works..?

Follow me, and see how it's work.

Step 5

  • Create Empty gameobject name it EventManager

Step 6

  • Create C# script and name it EventManager.

Write the following code into your script.

public class EventManager : MonoBehaviour {

	#region PUBLIC_VARIABLES
	public static EventManager Instance;
	public UnityEvent testEvent;
	#endregion

	#region UNITY_CALLBACKS
	void Awake(){
		Instance = this;
	}
	void Start(){
		StartCoroutine (TestEventDemo() );
	}
	#endregion
	
    #region CO_ROUTINES
    IEnumerator TestEventDemo(){
		yield return new WaitForSeconds(1f);
		testEvent.Invoke ();
	}
  	#endregion
}

Make sure your script imports/uses UnityEngine.Events.

Step 7

  • Assign it to EventManager (Empty GameObject).

Step 8

  • Open EventManager in Inspector window of Unity

UnityEventiIspector

Step 9

  • Select the + icon to add a slot for a callback.
  • Select the UnityEngine.Object you wish to receive the callback (You can use the object selector for this).
  • Select the function you wish to be called.
    UnityInspector2
  • You can add more then one callback for the event
    UnityEventInspector3

When configuring a UnityEvent in the Inspector there are two types of function calls that are supported:

  1. Static:
    • Static calls are preconfigured calls, with preconfigured values that are set in the UI.
    • This means that when the callback is invoked, the target function is invoked with the argument that has been entered into the UI.

  2. Dynamic:
    • Dynamic calls are invoked using an argument that is sent from code, and this is bound to the type of UnityEvent that is being invoked.
    • The UI filters the callbacks and only shows the dynamic calls that are valid for the UnityEvent.

I think one question is still in your mind.

It is easy to use because we can binds event in inspector window, no scripting no cognitive load..!!!

Then why UnityEvent has not much use as Event Delegates???

But Wait...

Now I will tell you some major cons of UnityEvent..

The main GC calls.

Let’s take an example to see the difference

In this example, I've used our previously created mini game for Event Delegate,

(link for Event project)

Run the unity and see profiler window,

EventDelegateProfiler

Now do Some changes in EventManager and make use of UnityEvents instead of Event Delegates.

(link for UnityEvents)

and run the Unity and see profiler window

UnityEvent Profiler

Direct double GC !!!!!!! Surprised..?

This is because once you bind(couple) the event in using window you can not decouple the events at run time as you done in Event Delegate using ‘-=’ operator.

Conclusion


  • UnityEvent creates more garbage than C# events.
  • It creates garbage when dispatched where C# events do not.
  • And it’s at least twice as slow as C# events.

Feel free to contact us if you really liked this blog. And don’t forget to share your comments below!

TheAppGuruz is a leading Mobile Game development company in India. We are proficient in Unity and we have design & developed 500+ Android and iOS mobile games for various client across the globe. If you have any game project that need professional help feel free to contact us.

We provide mobile game development services in countries like US, UK, Australia, UAE, Kuwait, Qatar, India, China, Indonesia, Singapore and European countries

Tune in to our social media for the latest on  Facebook | Twitter | Linkedin | YouTube.

Passionate game lover, professional game developer. Enthusiastic about work & believe in teamwork. Part of TheAppGuruz Team. Always work with challenges and do more creative & Innovative work which increase my knowledge and strength about Game Development.