[text] eventsystem

Viewer

copydownloadembedprintName: eventsystem
  1. using UnityEngine;
  2. using System.Collections.Generic;
  3.  
  4. // event system without arguments
  5. public static class EventSystem
  6. {
  7.     private static Dictionary<EventType, System.Action> eventDictionary = new Dictionary<EventType, System.Action>();
  8.  
  9.     public static void AddListener(EventType type, System.Action function)
  10.     {
  11.         if (!eventDictionary.ContainsKey(type))
  12.         {
  13.             eventDictionary.Add(type, null);
  14.         }
  15.  
  16.         eventDictionary[type] += (function);
  17.     }
  18.  
  19.     public static void RemoveListener(EventType type, System.Action function)
  20.     {
  21.         if (eventDictionary.ContainsKey(type))
  22.         {
  23.             eventDictionary[type] -= (function);
  24.         }
  25.     }
  26.  
  27.     // execute event for all those listening
  28.     public static void InvokeEvent(EventType type)
  29.     {
  30.         if (eventDictionary.ContainsKey(type))
  31.         {
  32.             eventDictionary[type]?.Invoke();
  33.         }
  34.     }
  35. }
  36.  
  37. // event system that takes arguments
  38. public static class EventSystem<T>
  39. {
  40.     private static Dictionary<EventType, System.Action<T>> eventDictionary = new Dictionary<EventType, System.Action<T>>();
  41.  
  42.     public static void AddListener(EventType type, System.Action<T> function)
  43.     {
  44.         if (!eventDictionary.ContainsKey(type))
  45.         {
  46.             eventDictionary.Add(type, null);
  47.         }
  48.  
  49.         eventDictionary[type] += (function);
  50.     }
  51.  
  52.     public static void RemoveListener(EventType type, System.Action<T> function)
  53.     {
  54.         if (eventDictionary.ContainsKey(type))
  55.         {
  56.             eventDictionary[type] -= (function);
  57.         }
  58.     }
  59.  
  60.     // execute event for all those listening
  61.     public static void InvokeEvent(EventType type, T arg)
  62.     {
  63.         if (eventDictionary.ContainsKey(type))
  64.         {
  65.             eventDictionary[type]?.Invoke(arg);
  66.         }
  67.     }
  68. }
  69.  

Editor

You can edit this paste and save as new:


File Description
  • eventsystem
  • Paste Code
  • 29 Mar-2022
  • 1.83 Kb
You can Share it: