Created
June 3, 2023 23:17
-
-
Save onewinter/28e52a48cfc64adb05dd30baca15cd89 to your computer and use it in GitHub Desktop.
An updated version of https://gist.github.com/onewinter/ce46fd5091ffd3e3ec8bf429e6d49ce7 using standard Events subscriptions instead of Lists
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using UnityEngine; | |
public class BaseGameEvent : ScriptableObject | |
{ | |
#if UNITY_EDITOR | |
[TextArea] public string developerDescription = ""; | |
#endif | |
public event Action Raised; | |
public void Raise() => Raised?.Invoke(); | |
} | |
public abstract class BaseGameEvent<T1> : BaseGameEvent | |
{ | |
public new event Action<T1> Raised; | |
public void Raise(T1 t1) => Raised?.Invoke(t1); | |
} | |
public abstract class BaseGameEvent<T1,T2> : BaseGameEvent | |
{ | |
public new event Action<T1, T2> Raised; | |
public void Raise(T1 t1, T2 t2) => Raised?.Invoke(t1, t2); | |
} | |
/* USE: | |
************* | |
[CreateAssetMenu()] | |
public class GameEvent : BaseGameEvent {} | |
public class IntGameEvent : BaseGameEvent<int> {} | |
public class IntStringGameEvent : BaseGameEvent<int,string> {} | |
************** | |
*/ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// | |
/// examples of the three components required to utilize the system: | |
/// | |
// the Scriptable Object Event definition | |
[CreateAssetMenu] | |
public class CoinGameEvent : BaseGameEvent<int> | |
{} | |
// the MonoBehaviour on each Coin to collect | |
public class Coin : MonoBehaviour | |
{ | |
// the Scriptable Object Event we created via the Create Asset menu | |
[SerializeField] private CoinGameEvent coinEvent; | |
// raise our coin event whenever the user picks up a coin | |
void OnTriggerEnter2D(Collider2D other) | |
{ | |
coinEvent.Raise(1); | |
Destroy(gameobject); | |
} | |
} | |
// this can also be a ScriptableObject since they still have OnEnable() and OnDisable() methods | |
public class CoinManager : MonoBehaviour | |
{ | |
int coins; | |
// register to Listen for the Coin Event | |
void OnEnable() => coinEvent.Raised += AddCoins; | |
void OnDisable() => coinEvent.Raised -= AddCoins; | |
// add the number of coins in the Event to our total | |
void AddCoins(int value) => coins += value; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment