Sitemap
Lem Apperson

Lem Apperson

Seeking employment using Uniy3D software solutions. Learning C++ and Unreal to expand my skills.

Beginning Game Development Scriptable Object as Event Handlers

Using Scriptable Objects as Event Handlers in Unity

4 min readJun 24, 2024

--

Press enter or click to view image in full size

In the realm of game development with Unity, managing communication between various game components can often become complex and cumbersome. Traditionally, developers might rely on singletons or direct references to connect different parts of their code. However, Unity offers a more modular and decoupled approach: using Scriptable Objects as event handlers. This method not only enhances code organization but also promotes reusability and maintainability.

Introduction to Scriptable Objects

Scriptable Objects in Unity are a powerful data structure that allows you to store data in a more modular and reusable manner. They are essentially assets that can hold data and logic, making them ideal for defining events and handling their behaviors. By using Scriptable Objects as event handlers, you can create a centralized system for managing game events, reducing the need for direct connections between different game components.

Creating a Scriptable Object for Events

To start, let’s create a Scriptable Object that will act as our event handler. This object will store a list of listeners and notify them whenever the event is raised.

Press enter or click to view image in full size

Step-by-Step Implementation

1. Define the Scriptable Object

using System.Collections.Generic;
using UnityEngine;

[CreateAssetMenu(fileName = "NewGameEvent", menuName = "Events/GameEvent")]
public class GameEvent : ScriptableObject
{
// The list of listeners that the event will notify if it is raised
private List<GameEventListener> listeners = new List<GameEventListener>();

// Method to register a listener
public void RegisterListener(GameEventListener listener)
{
if (!listeners.Contains(listener))
{
listeners.Add(listener);
}
}

// Method to unregister a listener
public void UnregisterListener(GameEventListener listener)
{
if (listeners.Contains(listener))
{
listeners.Remove(listener);
}
}

// Method to raise the event and notify all listeners
public void Raise()
{
for (int i = listeners.Count - 1; i >= 0; i - )
{
listeners[i].OnEventRaised();
}
}
}

2. Create a Listener Component

Next, we need a listener component that will react to the events raised by our Scriptable Object. This component will be attached to game objects that need to respond to specific events.

using UnityEngine;
using UnityEngine.Events;
public class GameEventListener : MonoBehaviour
{
[SerializeField]
private GameEvent gameEvent;
[SerializeField]
private UnityEvent response;
private void OnEnable()
{
gameEvent.RegisterListener(this);
}
private void OnDisable()
{
gameEvent.UnregisterListener(this);
}
public void OnEventRaised()
{
response.Invoke();
}
}
Press enter or click to view image in full size

3. Setting Up in Unity

- Create a new Scriptable Object asset by right-clicking in the Project window, selecting `Create > Events > GameEvent`, and giving it a name.
- Attach the `GameEventListener` component to any game object that should respond to the event.
- Assign the newly created `GameEvent` asset to the `gameEvent` field of the `GameEventListener` component.
- Define the response in the `UnityEvent` field, specifying what should happen when the event is raised.

4. Raising the Event

To raise the event, simply call the `Raise` method on the `GameEvent` Scriptable Object

public class SomeGameLogic : MonoBehaviour
{
[SerializeField]
private GameEvent someGameEvent;
private void Update()
{
if (Input.GetKeyDown(KeyCode.Space))
{
someGameEvent.Raise();
}
}
}

Benefits of Using Scriptable Objects as Event Handlers

1. Decoupling Components: By using Scriptable Objects as event handlers, you eliminate the need for direct references between different game components. This decoupling makes your code more modular and easier to manage.
2. Reusability: Scriptable Objects can be reused across different scenes and projects, promoting a DRY (Don’t Repeat Yourself) approach.
3. Centralized Event Management: Managing events through Scriptable Objects provides a centralized system where all events are defined and handled, making the overall event flow more transparent and maintainable.

Press enter or click to view image in full size

Conclusion

Using Scriptable Objects as event handlers in Unity is a powerful technique that simplifies event management, enhances code reusability, and maintains a clean architecture. By following the steps outlined above, you can implement a robust event system that keeps your game components loosely coupled and highly cohesive. This approach not only improves your workflow but also prepares your projects for future scalability and maintainability.

Get Lem Apperson’s stories in your inbox

Join Medium for free to get updates from this writer.

By integrating Scriptable Objects as event handlers, you harness the full potential of Unity’s architecture, ensuring your game development process remains efficient and effective.

--

--

Written by Lem Apperson

Seeking employment using Uniy3D software solutions. Learning C++ and Unreal to expand my skills.