Skip to content

Instantly share code, notes, and snippets.

@attilam
Last active April 20, 2021 15:36
Show Gist options
  • Save attilam/3999739 to your computer and use it in GitHub Desktop.
Save attilam/3999739 to your computer and use it in GitHub Desktop.
Generic message-based GameEvent Class for Unity
using UnityEngine;
using System.Collections;
public delegate void GameEventDelegate(GameEvent evt = null);
[System.Serializable]
public class GameEvent {
public GameObject target;
public GameObject instigator;
public string message;
#if USE_PLAYMAKER
public bool fsmEvent = false;
#endif
public SendMessageOptions messageOptions = SendMessageOptions.DontRequireReceiver;
public string tag;
public bool activateTarget = false;
public bool once = false;
public float retriggerDelay = 0;
[System.NonSerialized]
public float lastTriggered = Mathf.NegativeInfinity;
public string stringParam;
public float floatParam;
public bool boolParam;
public GameObject objectParam;
public bool Trigger( GameObject _instigator = null ) {
if (once && lastTriggered > 0)
return false;
if (lastTriggered+retriggerDelay > Time.time)
return false;
if (instigator == null)
instigator = _instigator;
lastTriggered = Time.time;
if (target) {
if (activateTarget) {
#if UNITY_3_5 || UNITY_3_4
target.SetActiveRecursively(true);
#else
target.SetActive(true);
#endif
}
#if USE_PLAYMAKER
if (fsmEvent) {
PlayMakerFSM fsm = target.GetComponent<PlayMakerFSM>();
if (fsm == null) {
Debug.LogError("GameEvent:Trigger: target doesn't have FSM.");
return false;
}
if (message == "")
message = "Trigger";
fsm.SendEvent(message);
}
else {
#endif
target.BroadcastMessage(message, this, messageOptions);
#if USE_PLAYMAKER
}
#endif
}
if (tag != "") {
GameObject[] targetList = GameObject.FindGameObjectsWithTag(tag);
foreach(GameObject go in targetList) {
if (activateTarget) {
#if UNITY_3_5 || UNITY_3_4
go.SetActiveRecursively(true);
#else
go.SetActive(true);
#endif
}
go.BroadcastMessage(message, this, messageOptions);
}
}
return true;
}
}
@attilam
Copy link
Author

attilam commented Nov 9, 2014

Add to MonoBehaviours, like this:

public class MyGO : MonoBehaviour {
    public GameEvent someEvent;

    // in a script you trigger the event like this
    public void TriggerEvent() {
        someEvent.Trigger(gameObject);
    }

    // Event handler, "MyEvent" is set as message in GameEvent
    public void MyEvent(GameEvent ev = null) {
        Debug.Log("MyEvent triggered by ", ev.instigator);
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment