Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //The commented lines can be restored if the project contains the Odin Inspector
- using System;
- using System.Collections.Generic;
- using UnityEngine;
- using UnityEngine.Events;
- //using Sirenix.OdinInspector;
- //Add this component to a gameobject to listen for global events, and fire
- //an instance of unity event (set up in inspector) in response.
- public class GlobalEventListener : MonoBehaviour {
- public string GlobalEventName;
- public UnityEvent OnGlobalEventInvoked;
- //[DisableInEditorMode, Button, HorizontalGroup(Title = "Debug")]
- public void DebugGlobalEventDictionary() {
- GlobalEvent.DebugDictionary();
- }
- //[DisableInEditorMode, Button, HorizontalGroup(Title = "Debug")]
- public void InvokeGlobalEvent() {
- GlobalEvent.Invoke(GlobalEventName);
- }
- //[DisableInEditorMode, Button, HorizontalGroup(Title = "Debug")]
- public void InvokeListenerEvent() {
- OnGlobalEventInvoked.Invoke();
- }
- private void OnEnable() {
- GlobalEvent.Subscribe(GlobalEventName, InvokeListenerEvent);
- }
- private void OnDisable() {
- GlobalEvent.Unsubscribe(GlobalEventName, InvokeListenerEvent);
- }
- }
- //GlobalEvents can be fired from any code by calling GlobalEvent.Invoke(string)
- public static class GlobalEvent {
- static Dictionary<string, Action> EventDictionary = new Dictionary<string, Action>();
- public static void DebugDictionary() {
- foreach (string key in EventDictionary.Keys) {
- int count = 0;
- Action _action;
- if (EventDictionary.TryGetValue(key, out _action)) {
- count = _action.GetInvocationList().Length;
- }
- Debug.Log("GlobalEvent " + key + ": " + count);
- }
- }
- public static void Subscribe(string name, Action action) {
- Action _action;
- if (EventDictionary.TryGetValue(name, out _action)) {
- _action += action;
- EventDictionary[name] = _action;
- }
- else {
- EventDictionary.Add(name, action);
- }
- }
- public static void Unsubscribe(string name, Action action) {
- Action _action;
- if (EventDictionary.TryGetValue(name, out _action)) {
- _action -= action;
- if (_action == null) {
- EventDictionary.Remove(name);
- }
- else {
- EventDictionary[name] = _action;
- }
- }
- }
- public static void Invoke(string name) {
- Action _action;
- if (EventDictionary.TryGetValue(name, out _action))
- _action.Invoke();
- else
- Debug.LogWarning("No subscribers to GlobalEvent: " + name);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement