Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
News - Blog: How to use C# Events in Unity

#1
Blog: How to use C# Events in Unity

The following blog post, unless otherwise noted, was written by a member of Gamasutra’s community.
The thoughts and opinions expressed are those of the writer and not Gamasutra or its parent company.


Objective


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

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.

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

Reply



Possibly Related Threads…
Thread Author Replies Views Last Post
  News - Pokemon Go December 2020 Events: Kyurem Raids, Mega Abomasnow, And More xSicKxBot 0 1,469 11-26-2020, 09:30 AM
Last Post: xSicKxBot
  News - GTA 5 Online's Halloween Continues With Bonuses In Extraterrestrial Events xSicKxBot 0 1,443 11-02-2020, 11:01 AM
Last Post: xSicKxBot
  News - Germany extends COVID-19 ban on events through August, affecting Gamescom 2020 xSicKxBot 0 1,516 04-17-2020, 10:47 AM
Last Post: xSicKxBot
  News - Blog: Scalable content management with Unity addressables xSicKxBot 0 1,603 01-03-2020, 03:32 PM
Last Post: xSicKxBot
  News - Blog: Handling Unity scene hierarchy and performance xSicKxBot 0 1,551 11-25-2019, 08:40 AM
Last Post: xSicKxBot
  News - Blog: From Air to Unity – The monstrous cloud editor under our bed xSicKxBot 0 1,662 09-13-2019, 09:46 PM
Last Post: xSicKxBot
  News - Blog: Unity Addressables – It’s never too big to fit xSicKxBot 0 1,717 09-08-2019, 02:46 PM
Last Post: xSicKxBot
  News - GameStop moving into esports with new events venue xSicKxBot 0 1,477 03-29-2019, 03:16 AM
Last Post: xSicKxBot
  News - Best of 2018: Gamasutra’s top games, devs, events and trends xSicKxBot 0 1,544 01-04-2019, 08:55 AM
Last Post: xSicKxBot
  News - Call of Duty: Black Ops 4 Holiday Events Announced xSicKxBot 0 2,891 12-26-2018, 04:15 PM
Last Post: xSicKxBot

Forum Jump:


Users browsing this thread:
1 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016