Link Demo: Event System With Scriptable Objects (Unity Play)
- José Luis Aguilera Luzania
- Ramón Antonio Sanchez Madrid
- Create an easy-to-use and customizable event system in Unity to remove strong reference dependencies between GameObjects.
- Provide a type of generic event that can be specialized for any type of data.
Is a behavioral design pattern that lets you define a subscription mechanism to notify multiple objects about any events that happen to the object they’re observing.
Please see: Observer (refactoring.guru) for a full explanation.
By default the package has five predefined events for data types: void
, int
, float
, bool
, string
.
VoidEventSO
: It is used when it is not necessary to send data to listeners.IntEventSO
: It is used when it is necessary to send data of type int to listeners.FloatEventSO
: It is used when it is necessary to send data of type float to listeners.BoolEventSO
: It is used when it is necessary to send data of type bool to listeners.StringEventSO
: It is used when it is necessary to send data of type strings to listeners.
- First declare the intEvent variable in your script of the type you need.
public IntEventSO intEvent;
- Create a callback function that will be called every time the event is invoked.
private void OnInt(int value)
{
// Do something.
}
- Register the callback function in the event in the OnEneable function.
private void OnEnable()
{
intEvent.AddObserver(OnInt);
}
- Unregister the callback function in the event in the OnDisable function.
private void OnDisable()
{
intEvent.RemoveObserver(OnInt);
}
- First declare the attribute in your script of the type you need.
public IntEventSO intEvent;
- Use the Invoke(T value) method when you want to notify listeners about something.
// code...
intEvent.Invoke(value);
// more code...
-
You can create event objects using the "Event SO" submenu in the create menu.
-
Assign the asset in the fields of the component that listens or invokes. You can also invoke the event using a button.
Invoke the event using a button.
Assign the assets to a script.
For this example let's make an event that sends a GameObject as a value when invoked.
-
First we need to create the
GameObjectEventSO
script. -
If you want to create your own event with its own data type you must first import the namespace
using Plugins.Event_System_SO.Scripts;
- Instead of inheriting from
MonoBehaviour
, we inherit fromEventOS
and between <> we specify the type of data that will be sent when the event is invoked, in this case GameObject.
public class GameObjectEventSO : EventSO<GameObject>
{
}
- Now we add the attribute
CreateAssetMenu
where we specify the submenu "Event SO" and the item "GameObject Event".
[CreateAssetMenu(menuName = "Events SO/GameObject Event")]
public class GameObjectEventSO : EventSO<GameObject>
{
}
- Now we can create our asset events that send GameObjects to listeners. We can also use buttons to invoke the events!
- TextMeshPro