Events and Delegates

Ive been using unity for a while now and have become more aware of certain types of systems and software design patterns that are being used. I have began some tutorials on events and delegates. I can see that they are neat and tidy and have good uses when you need to activate multiple game objects etc, but is there any other reason to be using them, and if so is there any good links for in game systems or patterns. Im trying to get to understand the professional level of games design.

I often use delegates for callbacks. For example, you might pass a function as a parameter to be called when a function completes. This is particularly useful for stuff that doesn’t happen instantly - e.g. a callback after a web asset is done loading. (Unity generally uses coroutines for this, but I much prefer callbacks - I actually have a wrapper class for WWW which loads a web asset and then calls a callback, so I don’t have to deal with coroutines.)

The Facebook API uses callbacks in this way, for stuff like when the player has logged in to FB.

Callbacks are also useful for ensuring one-way dependency, which is good software design. In other words, if you have class A which calls functions on class B, and class B which calls functions on class A, those two scripts are tightly couple and can never be separated. This code is fragile/brittle. However, let’s say that class A is more “fundamental” than class B. In a good software design, class A shouldn’t have any reference to B whatsoever, and deleting B from the project shouldn’t make A stop compiling. In this case, class B becomes responsible for BOTH directions of communication between them - and class A should have delegates/events to allow B to access it.

For a less abstract example, your in-game objects would be “A” and your game’s UI and controls would be “B”. The player character should have no references to the UI whatsoever. However, the UI still needs to know, for example, that the player’s health has dropped. So the player script has a OnHealthChanged event that your UI subscribes to. With this design, you can easily swap out your UI in the future - say you want a different UI for mobile vs desktop. Same for player controls - this would allow you to more easily make AI characters that are subject to the same input restrictions as the players are, or a control system that’s different on each platform.

2 Likes

One place I often use delegates is in state machines. Instead of dumping a bunch of if statements in Update, a much cleaner way is to just have a different method for each and to store which method you’d like to call in a delegate variable. There are other ways to do this, such as coroutines, but I often like this way.

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class StateMachineTest : MonoBehaviour
{
    delegate void State();
    State state;

    void Start()
    {
        state = Begin;
    }

    void Update()
    {
        if (state != null)
            state();
    }

    void Begin()
    {
        // if (some condition is met)
        state = Act;
    }

    void Act()
    {
        // Do the action

        // if (that action fails)
        state = Begin;
        // else
        state = End;
    }

    void End()
    {
        // Shut down
        state = null;
    }
}
2 Likes

It’s very common in my current project that I’ll use callbacks in combination with coroutines like this:

using UnityEngine;
using UnityEngine.Events;

public class MyClass : MonoBehaviour {

    public void DoThings() {
        StartCoroutine(Routine(onComplete: () => print("things have been done")));
    }

    private IEnumerator Routine(UnityAction onComplete = null) {
        // do stuff
        yield return new WaitForSeconds(5);
        if(onComplete != null) {
            onComplete();
        }
    }
}

HACK EVERYTHING!

Would there be such a thing as too many events in a case where class A needs to communicate with class B and vice versa?

There’s not a number that I would point to… since some things just need a lot of events. Like take for instance a gui element like a button, or a textfield… these will probably have 10,20, or even more events for all sorts of things from ‘mouse interactions’ to ‘keyboard interactions’ to ‘validation events’.

But then you might have another class that just has 8 or so events… but all so weird and off hand that it highlights a flaw in the design of that class. Like for instance if you had a data loader class and then you had events like ‘OnDataLoadedFromNet’ and ‘OnDataLoadedFromFile’ and ‘OnDataLoadedFromMyPocket’ and so on and so forth…

1 Like

It’s not a matter of numbers, really. If two classes genuinely need to be coupled, so be it, just be aware that they’ll be stuck together. If it doesn’t make conceptual sense for A to exist without B, and it doesn’t make sense for B to exist without A, then it’s fine to couple them.

1 Like

@lordofduct and @StarManta

Thanks! This really clears things up on how to manage events and not overdo it.