ruk·si

⬜️ Unity
Events

Updated at 2016-10-30 09:45
  • Use C# delegates if you only control the listeners in code.
  • Use Unity events if you want to control the listeners in code AND editor.
  • Don't use SendMessage messaging system, it's legacy crap.

C# delegates:

using System;
using UnityEngine;

public class Clock : MonoBehaviour
{
    public event Action TickBefore = delegate {};
    public event Action<float> TickAfter = delegate {};
    private void Start()
    {
        StartCoroutine(Timer());
    }
    private IEnumerator Timer()
    {
        var total = 0.0f;
        while (true) {
            TickBefore();
            return yield WaitForSeconds(1.0f);
            total += 1.0f;
            TickAfter(total);
        }
    }
}
using System;
using UnityEngine;

public class TickTock: MonoBehaviour
{
    public GameObject clock;
    private void OnEnable()
    {
        clock.TickBefore += OnTickBefore;
        clock.TickAfter += OnTickAfter;
    }
    private void OnDisable()
    {
        // TODO: Check if application is quitting.
        clock.TickBefore -= OnTickBefore;
        clock.TickAfter -= OnTickAfter;
    }
    private void OnTickBefore()
    {
        Debug.Log("Tick");
    }
    private void OnTickAfter(float total)
    {
        Debug.Log("Tock");
    }
}

Unity events:

using UnityEngine;
using UnityEngine.Events;

public class Eventor : MonoBehaviour
{
    public UnityEvent WaitAfter = new UnityEvent();
    private void Start()
    {
        StartCoroutine(Timer());
        WaitAfter.AddListener(OnWaitAfter);
    }
    private IEnumerator Timer()
    {
        yield return new WaitForSeconds(1.0f);
        WaitAfter.Invoke();
        WaitAfter.RemoveListener(OnWaitAfter);
        WaitAfter.RemoveAllListeners();
        WaitAfter.Invoke();
    }
    private void OnWaitAfter()
    {
        Debug.Log("Hello world!");
    }
}

Name events consistently. Personally I name them SubjectVerbWhen where the verb is always in present.

UpdateBefore
UpdateAfter
TitleChangeBefore
TitleChangeAfter