Events

Publisher

  • Uses Invoke.

Subscriber

  • 'subscribe' is done via 'myEvent += created_function'.

  • 'unsubscribe' is done via 'myEvent -= created_function'.

Creating events

  • Publisher:

using System;

public class MyScript_A : MonoBehaviour {

    // Creates the event, using 'arguments' like the event's 'EventArgs'.
    public event EventHandler<Arguments> OnPressSpace;

    // Function used as the 'Generic Parameter' for 'OnPressSpace'.
    public class Arguments : EventArgs {
        public int value;
    }
    
    private void Update() {
        if (Input.GetKeyDown(KeyCode.Space)) {
            // Fires the event with its argument.
            OnPressSpace?.Invoke(this, new Arguments {value = 2});
        }
    }
    
}
  • Subscriber:

using System;

public class MyScript_B : MonoBehaviour {

    private Start() {
        // Sets the variable 'myScript_A' to type 'MyScript_A' and stores the 'MyScript_A' component.
        MyScript_A myScript_A = GetComponent<MyScript_A>();

        // Subscribes: Accesses 'OnPressSpace' event from 'myScript_A' and "adds" the created function 'Event_OnPressSpace'.
        myScript_A.OnPressSpace += Event_OnPressSpace;
    }

    // Uses the created function 'Event_OnPressSpace' to receive the 'object' and 'arguments' passed during event firing.
    private void Event_OnPressSpace(object sender, myScript_A.Arguments e) {
        Debug.log("Value: " + e.value);
    }
    
}