#ScriptableObject proper event subscription & unsubscription

1 messages · Page 1 of 1 (latest)

zenith iris
#

In ScriptableObject

  • Awake is called when it is created and its name is changed
  • OnEnable is called when it is created, renamed by the user and the script is recompiled
  • Reset is called when it is created and reset by the user

I'm trying to properly subscribe and subscribe the events, the way it should be done, when the event is subscribed only once when needed.
The event should be subscribed when the script is added and recompiled, as that's when all the events are unsubscribed by Unity.
This is what OnEnable does. It, however, is also called when the ScriptableObject is renamed, which does cause the event being subscribed once more, and I'm also unable to properly unsubscribe it, as neither OnDestroy nor OnDisable are called before this happens.

Perhaps, there is some hidden method, which is only called when the ScriptableObject is created and the script is recompiled? Or is there any way to add the conditions for OnEnable, where I can manage the event subscription only when the script is not renamed?

pseudo crest
#

oh man, this is a fun topic

zenith iris
#

Additionally, I have created this extension methods in another class, which are called when the assets are imported, deleted and moved, with both the previous and new locations.

public static event Action<string[]> OnAssetsImported;

public static event Action<string[]> OnAssetsDeleted;

public static event Action<string[]> OnAssetsMovedTo;

public static event Action<string[]> OnAssetsMovedFrom;
pseudo crest
#

I'm pretty sure OnDisable gets called when the scriptable object is unloaded. That can happen if you switch scenes (in play mode) and there are no longer any references left to the object.

I wasn't aware that it didn't get called before something that winds up causing OnEnable to be called again

zenith iris
#

Yes, my only problem is in OnDisable, as, originally, I should be unsubscribing the events there

pseudo crest
#

Can you just unsubscribe from the event before you subscribe?

#

That might sidestep the problem.

zenith iris
pseudo crest
#

Right.

zenith iris
pseudo crest
#

haha, no problem :p

#

I don't know a good answer to the broader problem of "wtf is up with asset lifetimes?"