I have been playing around with events in Unity, specifically with a tutorial available about them (http://unity3d.com/learn/tutorials/modules/intermediate/scripting/events) and when I have only MonoBehaviour classes ( listeners and the event manager) my tests work as expected. However, now I am trying to do the same but using a listener that is a non -MonoBehaviour, it represents a state of my FSM, and the events are not triggered.
Question: In order to make events work, listeners have to be MonoBehaviour classes? If so, is there a workaround when the class is non MonoBehaviour ?
I found out what the problem was. I was using OnEnable and OnDisable to subscribe the events but in my non- MonoBehaviour class those functions are not available. So I have to use another methods to add and delete the events. Thanks
What I do is make a MonoBehaviour called RuntimeManager which is on an empty gameobject. In the non MonoBehaviour class I have OnAwake() for instance, and in RuntimeManager call OnAwake from Awake().
Ex.
using System;
using UnityEngine;
using System.Collections;
public class EventHolder
{
public event EventHandler Event01;
public void OnAwake()
{
Event01 += InvokeAction;
}
void InvokeAction(object o, EventArgs args)
{
return;
}
}
using UnityEngine;
using System.Collections;
public class RuntimeManager : MonoBehaviour
{
EventHolder eventHolder = new EventHolder();
void Awake()
{
eventHolder.OnAwake();
}
}