Events

What are Events?


Events in C# are a powerful way to implement communication between different parts of your code, especially when one script needs to react to changes in another.

Think of an event like a messenger. One script can send out a message (“Hey! Something happened!”) and other scripts can listen for that message and respond.

Basic Terminology

  • Event Sender: The class that defines and invokes the event.
  • Event Listener: The class that subscribes to the event and responds when it’s triggered.

Example:


Step 1: Define and Invoke an Event

C#
using UnityEngine;
using System;

public class Player : MonoBehaviour
{
    public static event Action OnPlayerDied;

    public int health = 100;

    public void TakeDamage(int damage)
    {
        health -= damage;
        if (health <= 0)
        {
            Debug.Log("Player died!");
            OnPlayerDied?.Invoke(); // Fire the event
        }
    }
}


Step 2: Listen/Subscribe to the Event

C#
using UnityEngine;

public class GameManager : MonoBehaviour
{
    private void OnEnable()
    {
        Player.OnPlayerDied += HandlePlayerDeath;
    }

    private void OnDisable()
    {
        Player.OnPlayerDied -= HandlePlayerDeath;
    }

    void HandlePlayerDeath()
    {
        Debug.Log("Game Manager received the death event. Game Over.");
    }
}


Event with Parameters

You can send extra info with the event.

C#
public static event Action<int> OnScoreChanged;

void AddScore(int points)
{
    score += points;
    OnScoreChanged?.Invoke(score);
}


Listener:

C#
private void OnEnable()
{
    ScoreManager.OnScoreChanged += UpdateUI;
}

void UpdateUI(int newScore)
{
    scoreText.text = "Score: " + newScore;
}


Best Practices

  • Unsubscribe in OnDisable() to prevent memory leaks
  • Use ?.Invoke() to check for null subscribers
  • Keep event names clear, like OnEnemyKilled, OnItemPickedUp

Leave a Comment

Your email address will not be published. Required fields are marked *