using System;
using System.Collections.Generic;
using UnityEngine;
public class EventSystem : MonoBehaviour
{
// Define a dictionary to store event listeners
private Dictionary<string, Action<object>> eventDictionary;
// Singleton pattern to ensure there's only one instance of the event system
private static EventSystem instance;
public static EventSystem Instance
{
get
{
if (instance == null)
{
instance = FindObjectOfType<EventSystem>();
if (instance == null)
{
GameObject obj = new GameObject("EventSystem");
instance = obj.AddComponent<EventSystem>();
}
}
return instance;
}
}
private void Awake()
{
// Initialize the event dictionary
eventDictionary = new Dictionary<string, Action<object>>();
}
public void AddListener(string eventName, Action<object> listener)
{
// Check if the event dictionary already has a listener for the given event name
if (eventDictionary.TryGetValue(eventName, out Action<object> thisEvent))
{
// If it does, add the new listener to the existing event
thisEvent += listener;
// Update the dictionary with the new event
eventDictionary[eventName] = thisEvent;
}
else
{
// If it doesn't, create a new event with the listener
thisEvent += listener;
eventDictionary.Add(eventName, thisEvent);
}
}
public void RemoveListener(string eventName, Action<object> listener)
{
// Check if the event dictionary has a listener for the given event name
if (eventDictionary.TryGetValue(eventName, out Action<object> thisEvent))
{
// Remove the listener from the event
thisEvent -= listener;
// Update the dictionary with the new event
eventDictionary[eventName] = thisEvent;
}
}
public void TriggerEvent(string eventName, object eventArgs)
{
// Check if the event dictionary has a listener for the given event name
if (eventDictionary.TryGetValue(eventName, out Action<object> thisEvent))
{
// Invoke the event with the given arguments
thisEvent.Invoke(eventArgs);
}
}
}
This code defines an EventSystem
class that allows objects in a Unity scene to communicate with each other by sending and receiving events.
The class uses a dictionary to store event listeners, with the event name as the key and a delegate of type Action<object>
as the value. The Action<object>
delegate allows events to pass any kind of object as an argument.
The class uses the singleton pattern to ensure that there’s only one instance of the EventSystem
in the scene.
The AddListener()
method adds a listener to an event by checking if the event dictionary already has an event with the given name. If it does, it adds the new listener to the existing event. If it doesn’t, it creates a new event with the listener.
The RemoveListener()
method removes a listener from an event by checking if the event dictionary has an event with the given name. If it does, it removes the listener from the event.
The TriggerEvent()
method triggers an event by checking if the event dictionary has an event with the given name. If it does, it invokes the event with the given arguments.