neuecc / UniRx

Reactive Extensions for Unity
MIT License
7.01k stars 895 forks source link

Upgrade ObservableEnableTrigger to handle multiple MonoBehaviours #466

Open ajcampbell1333 opened 3 years ago

ajcampbell1333 commented 3 years ago

I fixed two things in the ObservableEnableTrigger class:

1) The onEnable subject is null when it gets called the first time in OnEnable because OnEnable fires before OnEnableAsObservable(), so OnEnableAsObservable() does not work as expected until after you toggle it off/on. I fixed this race condition by putting the same code from OnEnable in Start as well. Due to the null-check, it fails quietly in OnEnable, so there's no need to worry about duplicate execution when it's in Start too.

2) I made the trigger able to handle lots of monobehaviours individually. For this goal, I added a dictionary that holds instances of a MonoListener class which associates each MonoBehaviour with its own unique onEnable and onDisable subjects. This way, when you call myMonoBehaviour.OnEnableAsObservable(), we funnel execution into the overridden version of OnEnableAsObservable, which injects the monobehaviour reference into trigger. Then, in addition to listening for on/off on the whole game object, we can also listen to on/off for each of the monobehaviours' enabled properties too.