Skip to main content

How to make an Event-System for unity - Technoob Technology

First, What is an Event-System? An Event-System is a collection of scripts we use to send messages between game objects without linking them through the Unity inspector. The best use of this is when you want to connect a game object of the scene to a prefab. Unity Engine doesn't allow us to do that through the inspector and the best way to get this done is by using an Event-System. What if you have 50 enemies in the game and you want to notify them all when the player dies. Without an Event-System we have to connect all the enemies to a manager or some kind of a script to do that... Think about having an array of 50 enemies. This can be solved easily using an Event-System. We will do a basic example of using this event system in the end of the article.


techoob technology unity event system


Well, now we know the advantages of using an Event-System. Lets start coding our own simple Event-System. First we have to get an idea on how this works.
techoob technology unity event system
First, a script in the scene raises an event using a static method of the event manager script. Then the event manager searches for the subscribed methods for that events and invokes them all. That is the simplest explanation for this. You'll get a better understanding when you reach the end of the article.



For the Event-System we need 3 different Scripts.
  1. EventManager script
  2. EventBehaviour script
  3. EventEnums script

01)Event Manager

First Lets Look at how the EventManager script is written.

techoob technology unity event system

Event Manager script has 3 static methods with a dictionary. The dictionary key is an enum which we have named as Event here and the value is a List of actions. We use an enum as the event we raise and listen to.. You can use a string or int or whatever you want. But this is very simple as you wont get any errors by mistyping event name or such problems. 

AddListener method takes two parameters. First one is the event enum and the second parameter is the method we want to invoke when the event is raised. We take the enum and check if the dictionary has a key as same as the enum Event we get. If there is a key then we add the method to the List of the enum key. If the dictionary doesn't contain the key then we create the key and a new action list and add the method to that list.

RemoveListener method works same as above but it remove the registered method from the list of the given event.



RaiseEvent method take a parameter of enum Event. It searches in the dictionary for a key as same as the enum Event we pass to the method and gets the list of actions related to that key. Then RaiseEvent method invokes all the methods in that list.

This is the basic explanation of how Event Manager works.

02)Event enum

The event enum we use is this.

techoob technology unity event system

There are two events as GameStart and GameOver.


03)Event Behaviour

Now we can use those 3 methods from other scripts to register and raise events. But to make this more user friendly we create another class inherited from the Unity monobehaviour. And we call it as EventBehaviour.

techoob technology unity event system

In the event behavior script there are two abstract methods and two virtual methods. We call the Subscribe method and OnEnable2 method when the game object is enabled using the OnEnable method provided by unity. We do the same for Unsubscribe method and OnDisable2 method to but when the gameobject is disabled using OnDisable method.

We use OnEnable2 and OnDisable2 methods to make sure that extended classes can use both OnEnable and OnDisable methods without Stopping the event registering.

Now when we create a new script which should use Event-Sytem we extend that script from this EventBehavior script as the example script shown below.
techoob technology unity event system

What we do is Extend the DemoScript from the EventBehaviour script. Then the IDE prompts us to Import missing abstract members. We add two methods to the EventManager using the AdListener method in the Subscribe method. And in the start method of the demo script we call the RaiseEvent method passing the GameStart Event enum to the method.. Then the event manager looks for the related methods and invokes the HandleOnGameLaunch event method. And in that method there is another event raise for the GameOver event. And then event manager invokes the HandleOnGameOverEvent method.



Using both event raise and listeners on the same script is not a practical use. So lets look at a practical use.



Example:

Now lets think there are some spheres in a scene. And we want them to change their color on a certain event.

First we add a new event to the Event enum called ColorChange.

techoob technology unity event system


Then we create a sphere controller script like this.

techoob technology unity event system

All we do here is registering the HandleOnColorChangeEvent on event manager for the ColorChange Event.

Then we add some spheres to the scene and add the SphereController script to all of them.

techoob technology unity event system

In addition we use a input manager script to raise the event when a specific button is pressed.

techoob technology unity event system



So when the E button is pressed we raise the ColorChange Event.

When we run the script and press the "E" button all the spheres would turn their color into red. It doesn't matter if have hundreds of spheres all would do the same thing if we have added the sphere controller to them.

techoob technology unity event system

 I hope you could get a better understanding on how to use this Event-System practically. We can improve an Event-System to send various data including classes with the event, so we can pass various data between game objects. Thats up to you to think how this can be improved for your uses. In Addition I will give you a small tip. You can use another enum to specify the state of the event like if the event is start or over using an enum. 





Comments

  1. Awesome guide to make our own event manager. Keep it up!

    ReplyDelete
  2. This is pretty nifty! How would you suggest handling a system like this where each event and corresponding action might require different arguments? Like, suppose I wanted the "ColorChange" event to have an associated Color value to change to?

    ReplyDelete

Post a Comment

Popular posts from this blog

How to make a first person character controller - Unity

A first-person character controller script is the starting point of any fps shooter game. Even new Unity game developers tend to write their own fps controller script before learning anything else as it is challenging and very exciting. In this article, we gonna create two simple fps controllers from scratch and will guide you step by step on how it works. First, let's understand the basic concept of an fps controller. You should have a rotating camera that rotates in the x-axis to look up and down and the character should rotate on the y-axis to look around. There are two ways to create an fps controller in the Unity Engine.  Using Character controller component Using the RigidBody component Both have different advantages and disadvantages when using them. It depends on your game to select the best fps controller according to your needs.  Character controller based fps controller Pros: Is grounded check is built-in Has its own methods to move the chara

Unity Get Post web requests - Technoob Technology

Web requests in unity are super easy to use. We gonna use the UnityWebRequest class as the WWW class is deprecated now. UnityWebRequest class can be used for both Get and Post methods. The 'UnityEngine.Networking' namespace is required to work with UnityWebRequests.  This tutorial is made with some simple UI elements. First Let's see how the GET method works. 01. UnityWebRequest.GET We use this method to receive data from the server as normal get requests. Using coroutines in web requests is mandatory as we have to wait until the download is complete before showing the results, and the coroutines make this much easier. A simple button calls the method and a text element will show the result. The script contains a reference to the text element and the string URL of your PHP file.  When the button is pressed the button executes the ButtonGetData method and that method simply starts the GetData coroutine. We use the using keyword as this data

How to make an Advanced Audio Manager for Unity - Technoob Technology

Unity engine gives us a good control on audio clips we use, But the problem is when we add several audio sources for several audio clips it's gonna get hard to control them all. And if you want to make some changes to only one audio source you have to find it first.  This will become a mess if you gonna work with more than 10 audio clips. In this case, we can Create an AudioManager and include all the audio clips in it and make some static methods to play, pause the audio from other scripts. This Audio Manager is written in C# and if you use unity-script you have to convert this into unity script first. In this tutorial, we gonna create an audio manager which contains 7 methods. 1.Play 2.Pause 3.Unpause 4.Stop 5.FadeIn 6.FadeOut 7.lower volume for a duration First, we need a Custom class which contains some strings, floats, bools and an audio clip. This class is not derived from unity mono behavior so we should add [System.Serializable] to mak