How to use C# Events in Unity

In this blog, I’ll explain you all about Events.

But wait…

If you are not aware with C# Delegates and how to use C# delegates in unity. so kindly, refere this blog first. Because it’s base concept of this blog.

What is problem with Delegates?

What is an Event?

Why Events are used?

How to declare an Event?

You may have all these questions in your mind.

Don’t worry, you are at the right place.

Let’s start, Do you remember the problem of Delegates?

If we use a single delegate after the use of multicast delegates then it will reset the existing invocation list.

This situation is very difficult to track if multiple classes subscribe to the same delegate.

This is the reason why we have Events.

Let’s see how they work.

Events are a type of special delegates which are used when you want to notify other classes when something happens. Like, on GameStart, on Gameover.

Let’s take a look on declaration and use of an Events.

1. Declare a Delegate

  • public delegate void OnGameStart();

2.Create an Event

  • public static event OnGameStart onGameStart;

3. Point to method

  • onGameStart += Move;

4. Invoke an Event

  • onGameStart ();

Let’s, create a simple game using Event Delegate.

Step 1

  • Create an empty GameObject name it as you like.

Step 2

  • Create C# script name it EventManager.

Write following code in EventManager.cs

  • public class EventManager : MonoBehaviour {
  • public delegate void OnButtonClick();
  • public static event OnButtonClick onButtonClick;
  • public void RaiseOnButtonClick() {
  • if (onButtonClick != null) {
  • onButtonClick();
  • }
  • }
  • }

Step 3

  • Assign it to an empty GameObject.

Step 4

  • Create a 2d object and assign knob as sprite in SpriteRenderer.

Step 5

  • Create  C# script name PlayerTransformAndColor.

Write following code in PlayerTransformAndColor.cs

  • public class PlayerTransformAndColor : MonoBehaviour {
  • public SpriteRenderer spriteRenderer;
  • public Color color1, color2;
  • private void OnEnable()
  • {
  • EventManager.onButtonClick += ChangePosition;
  • EventManager.onButtonClick += ChangeColor;
  • }
  • public void ChangePosition() {
  • transform.position += Vector3.one * 2;
  • }
  • public void ChangeColor() {
  • spriteRenderer.color = color2;
  • }
  • }

Step 6

  • Assign it to empty GameObject.

Now let’s do some changes in PlayerTransformAndColor.cs

  • public class PlayerTransformAndColor : MonoBehaviour {
  • public SpriteRenderer spriteRenderer;
  • public Color color1, color2;
  • private void OnEnable()
  • {
  • EventManager.onButtonClick += ChangePosition;
  • EventManager.onButtonClick += ChangeColor;
  • EventManager.onButtonClick = ChangeRotation;
  • }
  • public void ChangePosition() {
  • transform.position += Vector3.one * 2;
  • }
  • public void ChangeColor() {
  • spriteRenderer.color = color2;
  • }
  • public void ChangeRotation() {
  • transform.Rotate(0, 90, 0);
  • }
  • }

You may find the error. Like shown in below,

error

Got the  idea, How Events overcome the problem of Delegates.??

Events adds a layer of abstraction and protection on delegate, this protection prevents client of the delegate from resetting the delegate and invocation list.

Now let’s take one more practical example. That gives you more clear idea about how event handle multiple event listeners by only one event Invocation.

For this, we’ll follow these steps.

Step 1

  • Create an empty GameObject name it EventManager.

Step 2

  • Create C# scrip and name it Eventmanager.

Write following code in EventManager.cs

  • public class EventManager : MonoBehaviour {
  • public delegate void OnRest(); //Declare a Delegate
  • public static event OnRest onReset; //Create an Event
  • public delegate void OnReStart(); //Declare a Delegate
  • public static event OnReStart onReStart; //Create an Event
  • public static void RaiseOnReset()
  • {
  • if (onReset != null)
  • {
  • onReset(); //Invoke an Event
  • }
  • }
  • public static void RaiseOnReStart()
  • {
  • if (onReStart != null)
  • {
  • onReStart(); //Invoke an Event
  • }
  • }
  • }

Step 3

  • Assign it to an empty GameObject(EventManager).

Step 4

  • Create an empty GameObject name it EventHandler.

Step 5

  • Create C# script name it EventHandler

Write following code in EventHandler.cs

  • public class EventHandler : MonoBehaviour
  • {
  • void Update()
  • {
  • if (Input.GetKeyDown(KeyCode.P))
  • {
  • EventManager.RaiseOnReset(); // Function call to invoke an Event
  • }
  • else if (Input.GetKeyDown(KeyCode.S))
  • {
  • EventManager.RaiseOnReStart(); // Function call to invoke an Event
  • }
  • }
  • }

Step 6

  • Assign it to an empty Gameobject(EventHandler).

Step 7

Create a 3D game object(Cube).

Step 8

  • Create C# script name it ObjectMotion.

Write following code in ObjectMotion.cs

  • public class ObjectMotion : MonoBehaviour
  • {
  • private float minRange, maxRange;
  • private float speed, restartSpeed;
  • private Vector3 newPosition;
  • private void OnEnable()
  • {
  • EventManager.onReset += Reset;
  • EventManager.onReStart += Restart;
  • }
  • void Start()
  • {
  • minRange = 1;
  • maxRange = 3;
  • speed = Random.Range(minRange, maxRange);
  • restartSpeed = speed;
  • }
  • void Update()
  • {
  • newPosition = transform.position;
  • newPosition.x = Mathf.Sin(Time.time) * speed;
  • transform.position = newPosition;
  • }
  • private void OnDisable()
  • {
  • EventManager.onReset -= Reset;
  • EventManager.onReStart -= Restart;
  • }
  • public void Reset()
  • {
  • speed = 0;
  • }
  • public void Restart()
  • {
  • speed = restartSpeed;
  • }
  • }

Step 9

  • Assign it to 3D GameObject(Cube).

Now create multiple copies of 3D GameObject.

Run Unity, and press “P” to reset the position and “S” to restart the motion.

From the above examples we may come to the  following conclusion,

Conclusion

  • Delegates and Events help us to write modular and reusable code.
  • Always use Events together with Delegates for safety.
  • Do not forget to unsubscribe otherwise, it will lead to memory leak.

Before starting with Events please refer ‘Delegates in Unity’ blog post even if you haven’t already. That will clear your thoughts about Delegates which is the base concept for Events.

  • How to use C# Delegates in Unity

 

Leave a Comment

Your email address will not be published. Required fields are marked *