How to use Events in Unity 5

I wrote about Events a few years back. While the post is alright at covering the functionality behind the scenes, a much more straightforward approach is better most of the time.

pexels-photo (1)

Action!

.NET has the Action delegate built-in that will be enough for 90% of Event use cases and looks very neat. Actions can have 0 or more parameters so they’re very flexible.
MSDN documentation for Action<T>

A code example illuminates this the best so here’s one tha that shows all the basic operations of an Event; adding, removing, firing and receiving events.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
    // Events are declared as generic Action delegates. They can have 0 or more parameters.
    public Action<int, Vector3> OnEnemyHit;
 
    // Mock-function to add a new listener. Usually you would add this on Start() for example
    public void AddListener(){
        OnEnemyHit += EnemyHit;
    }
    
    // Mock-function to remove a listener.
    public void RemoveListener(){
        OnEnemyHit -= EnemyHit;
    }
 
    // Triggering the event
    public void Update(){
        if(enemy.wasHit) {
            if(OnEnemyHit != null){
                OnEnemyHit(enemy.id, enemy.position);
            }
        }
    }
 
    // Listener
    public void EnemyHit(int enemyID, Vector3 hitPosition){
        Debug.Log("Hit enemy: " + enemyID);
        Debug.Log(hitPosition.ToString());
    }
	// Events are declared as generic Action delegates. They can have 0 or more parameters.
	public Action<int, Vector3> OnEnemyHit;

	// Mock-function to add a new listener. Usually you would add this on Start() for example
	public void AddListener(){
		OnEnemyHit += EnemyHit;
	}
	
	// Mock-function to remove a listener.
	public void RemoveListener(){
		OnEnemyHit -= EnemyHit;
	}

	// Triggering the event
	public void Update(){
		if(enemy.wasHit) {
			if(OnEnemyHit != null){
				OnEnemyHit(enemy.id, enemy.position);
			}
		}
	}

	// Listener
	public void EnemyHit(int enemyID, Vector3 hitPosition){
		Debug.Log("Hit enemy: " + enemyID);
		Debug.Log(hitPosition.ToString());
	}

As you can see it’s a very simple system so there’s not much to say. Other than use it!

  • Gabe

    I know that you posted it awhile ago, but I’m just now trying to learn how to use events in Unity/C#. My understanding was that the whole point of using events was so that you could avoid calling methods in your update loop. Is this wrong, or are you just triggering the event in the update loop for the sake of this example?