- Home /
Non-monobehavior editor script subscribing to delegate event and persisting on application reload
I am currently working on an editor tool and I have a DataManager class that holds a bunch of DataObjects. The manager needs to subscribe to a static DataChangeEvent delegate, which I do in the constructor.
However, I need the event subscription to remain even when Unity is quit and relaunched. Since this isn't a monobehavior and I don't have OnEnable and OnDisable and my thought is that since the DataManager is serialized but the event is static, the subscription will be forgotten on next application load. I'm unable to [InitializeOnLoad] as the Manager holds a bunch of data objects.
Am I missing something?
The alternative I'm considering is to use a scriptable object singleton with a Serialized List of DataManager's Actions so I can use the ScriptableObject's OnEnable to subscribe them at Unity launch.
Thanks in advance.
// pseudo code
public static class EventHandler
{
public delegate void OnDataChange(DataObject dataObject);
public static event OnDataChange DataChangeEvent;
}
[Serializable]
public class DataManager
{
[SerializeReference] public List<SomeDataObject> someDataObjects;
public DataManager()
{
EventHandler.DataChangeEvent += OnChange;
}
public void OnDestroy() // Called by a parent class if needed
{
EventHandler.DataChangeEvent -= OnChange;
}
public void OnChange()
{
// Some Logic
}
}
I don't have exact solution for your problem but here's some thoughts (and probably someone more experienced can help more in this)
I try to stay away from purely edit time events and if I need them I usually make manual register button etc. Automatic event subs in the edit time I have found unreliable.
You can of course try to insert the event subs to SO in the onenable but this is not covering all the use cases that happen in the normal game dev workflow in the Unity. For example nothing guarantees that the events are still there after compilation & play & resume to the edit mode. Also check the cases where the SO's onenable is actually called.
Whatever you do just remember to always automatically clear the registration before registering to avoid duplicates.
Hope you get it working somehow.. and if you do, please tell how :)