[SOLVED] What are the best practices for managing the complexity of UnityEvents?

Hi there -

I recently discovered UnityEvents (not to be confused with native C# events and delegates) and have been having a blast decoupling the hell out of my project. I eventually settled on an architecture where events are used to pass data between components, with each component processing the data in a perfectly encapsulated manner and then spitting it back out via another event.

While I was able to massively reduce the usage of GetComponent<>, I’ve now found myself growing more and more overwhelmed by the growing complexity of my event system. While it works perfectly from the “set and forget” standpoint (once I’ve hooked up the components that needed hooking up, I can move on and change things without anything breaking), it still feels like a virtual form of spaghetti code. Moreover, adding gameObject with an inherited class that contains UnityEvents means I have to both wire each of the new gameObject’s events to the existing framework and to update scripts in the existing framework to accommodate the newly created Event. Doing this in Inspector quickly gets cumbersome and, more importantly, increases the risk of error - all I need to do to make a mistake is to forget to make one connection.

I think a lot of this could be avoided by adding listeners during runtime (e.g., in Start, Awake, or OnEnable) - this, at least, would take care of UnityEvents in inheritance-driven classes. However, as far as I know, there’s no way to add a listener to a UnityEvent outside the class that declares that event. In other words, if the event is declared in Class A, there’s no way I can add listeners to it in Class B except via the Inspector - am I right?

Additionally, are there any best practices you can suggest for solutions that make extensive use of UnityEvents? I was thinking of creating something like a clearing house of events - a central class that all Events come to and that sends out events where appropriate, but I’m not at all sure whether this would help.

I should note that I’m working on a clicker-style game, so there aren’t a lot of cases of objects getting destroyed or disabled.

Many thanks in advance,
George

You can listen to events from other script by referencing the script. The event is just a public variable like any other.

public ScriptWithEventsInside eventScript;

void OnEnable()
{
    eventScript.EventName += FunctionToRun;
}

void FunctionToRun()
{
    //
}

Note, the above code is for regular C# events. I think with UnityEvents it would be eventScript.EventName.AddListener(FunctionToRun); or something.

Or you can make a static event, which is like a “global” variable, where you don’t have to reference the script, but you can’t hook these up in the inspector.

void OnEnable()
{
    ScriptWithEventsInside.StaticEventName += FunctionToRun;
}
void OnDisable()
{
    ScriptWithEventsInside.StaticEventName -= FunctionToRun;
}

void FunctionToRun()
{
    //
}

You can maybe remove some of the spaghetti by using a more centralized manager classes that the events go through.

You should try doing your events through code, instead of the inspector. You could lose all of those links just by changing the event’s code, possibly even just the name. I’ve only found using the inspector for simpler scripts, like a generic collision class that reports an event when a collision happens, and only when it will be listened to by scripts on the same gameobject/prefab.

I’m not a great programmer though, so try asking this guy: @lordofduct

Thanks a bunch for trying to help!

Unfortunately, the above doesn’t work - while it’s indeed possible to subscribe to C# events in other classes, I can’t seem to find a way to do it with UnityEvents. Here is the exact code for the sender class:

public class Skill : MonoBehaviour {

    [Serializable]
    public class SkillEvent : UnityEvent <Skill, int> { };
    public SkillEvent SkillIncrease;

}

…and for the receiver class:

public class ShowSkillIncreaseText : MonoBehaviour {

    public GameObject go;
    Skill skill;
    int amount;
 
    void Start()
        {
        Skill.SkillIncrease.AddListener(DisplayText);
        }

    public void DisplayText(Skill skill, int amount)
        {
        GameObject inst = Instantiate(go, transform);
        inst.GetComponent<SkillIncreaseText>().skill = skill;
        inst.GetComponent<SkillIncreaseText>().amount = amount;
        }
    }

The above code produces the “'An object reference is required for the non-static field, method, or property ‘Skill.SkillIncrease’”. Should I just make the thing static?

I agree - which is why I’m looking for a solution that adds listeners from outside the event’s own class. What I like about the UnityEvent system is that I can successfully use it with inheritance - meaning, I can point the event to inherited classes 3 and 4, but not 1 and 2. In contrast, using C# delegates led to situations where the same event was dispatched to all the classes deriving from the class that declared the event. The alternative to that was creating an individual event for every inherited class to govern its communication with the sender - which doesn’t sound terribly elegant.

The error is because you did “Skill.SkillIncrease.AddListener” instead of “skill”, so it’s looking at the base class as a whole, instead of the variable. You can only do that with Static events. Also, that variable is an empty Skill, not referencing one that exists somewhere else.

You have to do “skill = GetComponent();” to reference it. Or do “public Skill skill” and drag in a reference in the inspector.

Nope, there’s an AddListener method on UnityEvent:
https://docs.unity3d.com/ScriptReference/Events.UnityEvent.AddListener.html

Though, of course, the entire point of UnityEvent is to first and foremost offer event wiring through the inspector. If you’re only using them in code… why use UnityEvent?

So personally I don’t use UnityEvent. I built my own version of UnityEvent long before UnityEvent was created by Unity.

We call it a ‘Trigger’ on our team.

The big way we use them is as simple event drivers for my designer who doesn’t write code.

I write simple scripts that trigger on simple events like when an entity enters a trigger collider, or when the player performs and attack. My designer can then use various scripts that we call “i’s” (just because) to perform things like play an animations, or play a sound effect, or other designer oriented stuff like that.

t_EnterTrigger:
https://github.com/lordofduct/spacepuppy-unity-framework/blob/master/SpacepuppyBase/Scenario/t_EnterTrigger.cs

i_PlaySoundEffect:
https://github.com/lordofduct/spacepuppy-unity-framework/blob/master/SpacepuppyBase/Scenario/i_PlaySoundEffect.cs

i_Enable:
https://github.com/lordofduct/spacepuppy-unity-framework/blob/master/SpacepuppyBase/Scenario/i_Enable.cs

The ‘i_Enable’ is probably the most powerful for my designer… since it can be used to start and stop various events by enabling and disabling GameObjects.

So you walked into a room, entered a trigger box in the doorway, this enables a GameObject that represents a cutscene. The cutscene starts to play.

So, let me take another example from my code to better explain the issue. I have a base class called Activity which, in my clicker game, contains information about how much completing that activity pays out, how much experience it awards, etc etc. Actual activities - such as Activity A, Activity B, etc - all inherit from that class.

When the activity is triggered by clicking on it, progress towards completion is shown via a circular progress bar (handled via a separate script), which exists as a child object of each activity in the hierarchy. I currently have 8 such activities. Now, the trick is to communicate from one script to the other than the activity has been started and that the progress bar should start moving; and, once done, that the activity should pay out using the values described in the class.

Now, there are several ways I can think of to send the message from the activity to the progress bar:

  • In the Activity class, I can use GetComponentInChildren().StartProgressBar() - This is by far the easiest solution, but it breaks encapsulation completely since it requires the Activity class to know about the insides of the ProgressBar class. It also reinforces the connection between a logic class (Activity) and what is essentially a UI handler class (ProgressBar) - again, something that’s best avoided.
  • I can use a C# event to send a message from the Activity class to the ProgressBar class containing the data to be used (activity duration for the progress bar, for instance). I can then have a method in the ProgressBar class subscribed to the event which will trigger the progress bar upon receiving it. This is better (encapsulation and UI-logic separation are maintained) - however, it stops me from reusing the same ProgressBar class because when the event fires, it will be received by all instances of the ProgressBar class in the solution (of which there’s one for each activity). Unless there’s a way to limit the scope of the C# event to just the children of the sending class?
  • I can use UnityEvent delegates to specifically send messages from this Activity to its corresponding ProgressBar, but not to any other ProgressBars in the hierarchy. This basically works perfectly, except that it leads to proliferation of UnityEvents, over-reliance on the inspector, and an ever-increasing risk of human error (not to mention rapidly growing complexity).

Essentially, had there been a way to limit the reach of a C# event delegate, I’d have stuck with those - they’re nicely coded and do everything that UnityEvents do. But, absent such a limitation, I could think of no other way to send an event that targets specifically that ProgressBar and not any other.

Does it make sense? :slight_smile:

Hi all -

So, I’ve found my solution after all, which I’m posting here in case anyone finds it useful going forward. Essentially, I separated my event-related cases into two categories - those where there is a clear hierarchical relationship between the two components (for example, one component triggers something in a child gameObject) and those where there isn’t one (for example, one component triggers the income calculation method in a separate module).

I switched back to C# events (so, so much cleaner) and, for hierarchical relationships, declared events as public but not static and made use of GetComponentInChildren / GetComponentInParent - which enabled me to prevent situations an event was sent to all instances of the receiving class, like so:

public class Sender: MonoBehaviour {

    public delegate void ActivityStart (float data);
    public event ActivityStart OnActivityStart;
}
public class Receiver: MonoBehaviour {

void Start () { GetComponentInParent<Sender>().OnActivityStart += ReceivingMethod; }

void ReceivingMethod(float data)
{
// Do something with the data;
}

In contrast, for non-hierarchical relationships - where I expect the receiver to be completely outside the sender’s hierarchy - I used static events, like so:

public class Sender: MonoBehaviour {

    public delegate void ActivityStart (float data);
    public static event ActivityStart OnActivityStart;
}
public class Receiver: MonoBehaviour {

void Start () { Sender.OnActivityStart += ReceivingMethod; }

void ReceivingMethod(float data)
{
// Do something with the data;
}

Another way to look at it is that communications with what were essentially singleton receivers could be handled via static events, while communications with non-singletons were handled via the more restricted public events.

3 Likes