HI, I recently started looking into scriptable objects, and found a highly referenced video from one of Unity's tedtalks a few years ago about scriptableobject events. Ive also looked at a few different videos that basically explained the same thing, but I wanted to see if they had something new to add, and surprisingly no, it's generic code that is basically a universal "event" component that has an event that triggers, and what the response will be; looks very flexible. I personally always struggled with the concept of normal unity events, both simantics and logic flow in general. Code below.
A few questions:
Why doesnt unity just keep this code as a draggable component in the inspector from unity's out-the-box code? The code is so generic and reusable since the set up is done, now u just have to connect the actual event and response functions that you just drag and drop, similar to other components.
I also noticed that one of the videos I saw had used the same GameEventListener.cs multiple times, so I'm assuming this requires that each event needs its own GameEventListener.cs component ? So basically unlike scripting where u can keep different systems, (ex.: character controller input event > playerobject action delegate in controller.cs, player.cs health drop event > UI slider delegate, etc). So with scriptableobject events, specifically this script, I could reduce code without needing those examples in the previous sentence, but the player object would neeeed to have a bunch of different GameEventListener.cs components attached per event right ? Since only one event can "invokes" the response() list in the script?
Regarding the last question, is this a relatively efficient way of doing this? I'm just surprised since at face value the code makes sense, but I'm not used to seeing a GO have multiple of the same components, and with this method, it looks like a singular GO could have MANY of the same GameEventListener.cs, one per event (and then one or multiple responses).
// ----------------------------------------------------------------------------
// Unite 2017 - Game Architecture with Scriptable Objects
//
// Author: Ryan Hipple
// Date: 10/04/17
// ----------------------------------------------------------------------------
using System.Collections.Generic;
using UnityEngine;
namespace RoboRyanTron.Unite2017.Events
{
[CreateAssetMenu]
public class GameEvent : ScriptableObject
{
/// <summary>
/// The list of listeners that this event will notify if it is raised.
/// </summary>
private readonly List<GameEventListener> eventListeners =
new List<GameEventListener>();
public void Raise()
{
for(int i = eventListeners.Count -1; i >= 0; i--)
eventListeners[i].OnEventRaised();
}
public void RegisterListener(GameEventListener listener)
{
if (!eventListeners.Contains(listener))
eventListeners.Add(listener);
}
public void UnregisterListener(GameEventListener listener)
{
if (eventListeners.Contains(listener))
eventListeners.Remove(listener);
}
}
}