Hi all,
I just completed the Unity Event System live training tutorial over here: http://unity3d.com/learn/tutorials/modules/intermediate/live-training-archive/events-creating-simple-messaging-system
I’m trying to decouple my scripts using the above system, but I can’t figure out how to send a variable from the EventManager.TriggerEvent() to my listener. I’m using the exact same EventManager code as the tutorial, but I’ll paste it here for easy reference.
Basically I’m trying to call my GUI script to update the Player’s coin amount via the event system. I’ve added comments on the lines that needs fixing.
EventManager
using UnityEngine;
using UnityEngine.Events;
using System.Collections;
using System.Collections.Generic;
public class EventManager : MonoBehaviour {
private Dictionary <string, UnityEvent> eventDictionary;
private static EventManager eventManager;
public static EventManager instance
{
get
{
if (!eventManager)
{
eventManager = FindObjectOfType (typeof (EventManager)) as EventManager;
if (!eventManager)
{
Debug.LogError ("There needs to be one active EventManger script on a GameObject in your scene.");
}
else
{
eventManager.Init ();
}
}
return eventManager;
}
}
void Init ()
{
if (eventDictionary == null)
{
eventDictionary = new Dictionary<string, UnityEvent>();
}
}
public static void StartListening (string eventName, UnityAction listener)
{
UnityEvent thisEvent = null;
if (instance.eventDictionary.TryGetValue (eventName, out thisEvent))
{
thisEvent.AddListener (listener);
}
else
{
thisEvent = new UnityEvent ();
thisEvent.AddListener (listener);
instance.eventDictionary.Add (eventName, thisEvent);
}
}
public static void StopListening (string eventName, UnityAction listener)
{
if (eventManager == null) return;
UnityEvent thisEvent = null;
if (instance.eventDictionary.TryGetValue (eventName, out thisEvent))
{
thisEvent.RemoveListener (listener);
}
}
public static void TriggerEvent (string eventName)
{
UnityEvent thisEvent = null;
if (instance.eventDictionary.TryGetValue (eventName, out thisEvent))
{
thisEvent.Invoke ();
}
}
}
EventTriggerTest
using UnityEngine;
using System.Collections;
public class EventTriggerTest : MonoBehaviour {
void Update () {
if (Input.GetKeyDown ("q"))
{
EventManager.TriggerEvent ("coinUpdate"); // How do I pass the coin amount from here?
}
}
}
EventTest
using UnityEngine;
using UnityEngine.Events;
using System.Collections;
public class EventTest : MonoBehaviour {
private UnityAction coinUpdateListener;
void Awake ()
{
coinUpdateListener = new UnityAction (UpdateCoinAmount); // This line needs fixing?
}
void OnEnable ()
{
EventManager.StartListening ("coinUpdate", coinUpdateListener);
}
void OnDisable ()
{
EventManager.StopListening ("coinUpdate", coinUpdateListener);
}
void UpdateCoinAmount(int amount)
{
Debug.Log ("Update amount " + amount);
}
}
Thanks!