Skip to content

Instantly share code, notes, and snippets.

@mandarinx
Created February 21, 2018 13:44
Show Gist options
  • Save mandarinx/b742755c14bd68b2bdf660ef82f630ef to your computer and use it in GitHub Desktop.
Save mandarinx/b742755c14bd68b2bdf660ef82f630ef to your computer and use it in GitHub Desktop.
Game Events as ScriptableObjects

Game Events as ScriptableObjects

Put GameEventInspector.cs in an Editor folder. After Unity's done compiling, pick a folder where you want to put your GameEvent asset. Right click in the folder view, click on Create/Game Events/GameEvent.

using System;
using System.Collections.Generic;
using UnityEngine;
namespace GameEvents {
[CreateAssetMenu(menuName = "Game Events/GameEvent")]
public class GameEvent : ScriptableObject {
private readonly List<GameEventListener> eventListeners = new List<GameEventListener>();
private Action callbacks = () => { };
public void Invoke() {
for (int i = eventListeners.Count - 1; i >= 0; i--) {
eventListeners[i].OnEventRaised();
}
callbacks.Invoke();
}
public void RegisterListener(GameEventListener listener) {
if (!eventListeners.Contains(listener)) {
eventListeners.Add(listener);
}
}
public void UnregisterListener(GameEventListener listener) {
eventListeners.Remove(listener);
}
public void RegisterCallback(Action callback) {
callbacks -= callback;
callbacks += callback;
}
public void UnregisterCallback(Action callback) {
callbacks -= callback;
}
}
}
using UnityEditor;
using UnityEngine;
namespace GameEvents {
[CustomEditor(typeof(GameEvent))]
public class GameEventInspector : Editor {
public override void OnInspectorGUI() {
base.OnInspectorGUI();
GUI.enabled = Application.isPlaying;
if (GUILayout.Button("Invoke")) {
(target as GameEvent)?.Invoke();
}
}
}
}
using UnityEngine;
using UnityEngine.Events;
namespace GameEvents {
public class GameEventListener : MonoBehaviour {
[Tooltip("Event to register with.")]
public GameEvent gameEvent;
[Tooltip("Response to invoke when gameEvent is raised.")]
public UnityEvent response;
private void OnEnable() {
gameEvent.RegisterListener(this);
}
private void OnDisable() {
gameEvent.UnregisterListener(this);
}
public void OnEventRaised() {
response.Invoke();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment