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. C# (CSharp) UnityEngine.Events UnityEvent - 30 examples found. These are the top rated real world C# (CSharp) examples of UnityEngine.Events.UnityEvent extracted from open source projects. You can rate examples to help us improve the quality of examples. Programming Language: C# (CSharp). C# (CSharp) UnityEngine.Events UnityEvent.AddListener - 9 examples found. These are the top rated real world C# (CSharp) examples of UnityEngine.Events.UnityEvent.AddListener extracted from open source projects. You can rate examples to help us improve the quality of examples. Unity’s Scriptable Render Pipeline (SRP) is a feature that allows you to control rendering via C# scripts. SRP is the technology that underpins the Universal Render.
UnityEventhas several generic overloads which you can use to add parameters (such as strings, ints, etc) Basically any data type Unity will serialize will show up in the inspector. So you basically need to use a UnityEventfor example if you wish to raise an event with a string. Hereis an example on using the single parameter UnityEvent.
Events are a key part of general C# development. In Unity, they can sometimes be overlooked and less optimal options are used. If you’ve never used events, you’ll be happy to know that they’re easy to get started with and add a lot of value to your project architecture.
Before I cover the Event system in detail, I’d like to go over some of the common alternatives you’ll see in Unity projects.
BroadcastMessage
The BroadcastMessagemethod is part of the MonoBehaviour class. It allows you to send a loosely coupled message to all active gameobjects.
BroadcastMessage is simple to use and accomplishes the task of sending a message from one gameObject to another.
The biggest issue with BroadcastMessage is how it refers to the method that will be called. Because it takes a string as the first parameter, there is no compile time verification that the method actually exists.
It can be prone to typos, and it introduces danger when refactoring / renaming your methods. If the method name in the string doesn’t match the method name in your classes, it will no-longer work, and there’s no obvious indication of this beyond your game failing to work properly.
The other parameters are also not tightly coupled, so there’s no parameter verification. If your method required a string and an int, but you call BroadcastMessage with two strings, your call will fail, and again there’s no compile time indication of this issue.
Another bigdrawback to BroadcastMessage is the fact that it only broadcasts to children. For the example given, the UI Text would only receive the message if it’s a child of the player.
This does not work
Update Polling
Another common technique I see in Unity projects is polling properties in the Update() method.
Polling in an Update() method is fine for many things, but generally not the cleanest way to deal with cross gameobject communication.
In this example, we update the text of our UI every frame to match the HP value of the player. While this works, it’s not very extensible, it can be a bit confusing, and it requires us to make variables public that may not really need to be.
It also get a lot messier using Update Polling when we want to only do things on a specific situation. For updating the player HP UI, we may not mind doing it every frame, but imagine we want to play a sound effect when the player takes damage too, suddenly this method becomes much more complicated.
Events
If you’ve never coded an event, you’ve probably at least hooked into one before.
One built in Unity event I’ve written about recently is the SceneManager.sceneLoaded event.
This event fires whenever a new scene is loaded.
You can register for the sceneLoaded event and react to it like this.
Each event can have a different signature, meaning the parameters the event will pass to your method can vary.
In the example, we can see that the sceneLoaded event passes two parameters. The parameters for this event are the Scene and the LoadSceneMode.
Creating your own Events
Now, let’s see how we can build our own events and tie them into the example before.
In this example, we create a new delegate named PlayerTookDamageEvent which takes a single integer for our HP value.
Then we use the delegate to create an event named OnPlayerTookDamage.
Now, when we take damage, our Player class actually fires our new event so all listeners can deal with it how they like.
We have to check our event for null before calling it. If nothing has registered with our event yet, and we don’t do a null check, we’ll get a null reference exception.
Next, we need to registerfor this newly created event. To do that, we’ll modify the PlayerHPBar script like this.
To test our event, let’s use this PlayerDamager.cs script.
This script calls the TakeDamage() method on the Player every 5 seconds.
TakeDamage() then calls the OnPlayerTookDamage event which causes our PlayerHPBar to update the text.
Let’s see how this looks in action.
Example playing at 10x speed

We can see here that the players HP is decreasing and the text is updating.
You may have noticed something strange though. The first value shown is -1. This caught me off guard the first time, but the cause is visible in the code.
Before you continue reading, take a look and see if you can findit.
….
In our Player.cs script, we set the HP to 10 in the Start() method.
Our PlayerDamager.cs script also starts dealing damage in the Start() method.
Because our script execution order isn’t specified, the PlayerDamager script happens to be running first.
Since an int in c# defaults to a value of Zero, when TakeDamage() is called, the value changes to -1.
Unityevent Order
Fix #1
There are a few ways we can fix this.
We could change the script execution order so that Player always executes before PlayerDamager.
In the Script Execution Order screen, you can set the order as a number. Lower numbered scripts are run before higher numbered scripts.
Fix #2 – Better
While this would work, there’s a much simpler and cleaner option we can use.
We can change the Player.cs script to set our HP in the Awake() method instead of Start().
Awake() is always called before Start(), so script execution order won’t matter.
So now we have our event working, but we haven’t quite seen a benefit yet.
Let’s add a new requirement for our player. When the player takes damage, let’s play a sound effect that indicates that they were hurt.
PlayerImpactAudio
To do this, we’ll create a new script named PlayerImpactAudio.cs
Notice on line 13, we register for the same OnPlayerTookDamage event that we used in the PlayerHPBar.cs script.
One of the great things about events is that they allow multipleregistrations.
Because of this, we don’t need to change the Player.cs script at all. This means we’re less likely to break something.
If you’re working with others, you’re also less likely to need to do a merge with another developers code.
We’re also able to more closely adhere to the single responsibility principal.
The single responsibility principle states that every module or class should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by the class. All itsservices should be narrowly aligned with that responsibility.
Robert C. Martin expresses the principle as follows:[1] “A class should have only one reason to change.”
The GameObject & AudioSource
You may have also noticed line 5 which tells the editor that this component requires another component to work.
Here, we’re telling it that we need an AudioSource on the gameobject. We do this because line 11 looks for an AudioSource to play our sound effect from.
For this example, we’ve created a new gameobject and attached both our PlayerImpactAudioSource.cs script and an AudioSource.
Then we need to assign an AudioClip. As you can see in the example, I’ve recorded my own sound effect and named it “oww”.
Now when we hit play, a sound effect triggers every time the TakeDamage() method is called.
If this is all new to you, don’t worry, we’re almost done, and it gets easier.
Actions were added to c# with .net 2.0. They’re meant to simplify events by removing some of the ceremony around them.
Let’s take another quick look at how we defined the event in our Player.cs script.
First, we define the event signature, declaring that our event will pass one integer named “hp”.
Then we declare the event so that other code can register for it.
With Actions, we can cut that down to one line.
That’s all there is to it. Nothing else needs to change. All the other scripts work exactly the same. We’ve simply reduced the amount of code needed for the same effect.
While this is great for the majority of events, there is one reason you may want to still use the occasional event. That would be when your event has many parameters that can be easily confused with each other. My recommendation for that situation however is to re-think your events and see if the amount of data you’re passing is larger than it needs to be. If you really need to pass a lot of data to an event though, another great option is to create a new class or struct and fill it with your data, then pass that into the event.
Final Tip
Before I go, it’s also worth mentioning that you can have multiple parameters to an Action. To do this, simply comma separate your parameter types like this.
If you have questions or comments about Events or using Action, please leave a comment or send me an email.
Related
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.
Unityevent Invoke
Step 2
Unity Events Example
- Create Empty gameObject name it as you like.
Step 3
- Create C# script name it as you like.
Write following code in UnityEventDemo.cs.
Step 4
Unity Eventsystem
- 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.
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
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.
- You can add more then one callback for the event
When configuring a UnityEvent in the Inspector there are two types of function calls that are supported:
- 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.
- 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,
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
Unity Event Center Bessemer Al
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.
Different Ways Of Doing Sprite Sheet Animation In Unity

Comments are closed.