neuecc / UniRx

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

OnEnableAsObservable fails to trigger OnNext when component.enabled toggles #465

Closed ajcampbell1333 closed 4 years ago

ajcampbell1333 commented 4 years ago

When calling the extension method myMonoBehaviour.OnEnableAsObservable(), subscription only works if you toggle the enabled property of the game object or the trigger, not if you toggle the component. Same is true for OnDisable. This is because ObservableEnableTrigger listens to itself. When the trigger is created by the component extension method, the implication is that it will listen to its creator. Here's a pull request for an alternate version of OnEnableAsObservable() called OnMonoEnableAsObservable(), in which the trigger listens for a change of the enabled property of its creator component, rather than listening for its own OnEnable method.

ajcampbell1333 commented 4 years ago

Actually, I'm closing this as I discovered a problem with it. By the nature of needing to be associated with only one sibling component, this new ObservableMonoEnableTrigger cannot be created via the usual GetOrAdd as it would be overwritten if a second monobehaviour attempts to recreate it on the same game object. I have resolved this by keeping a dictionary which indexes component refs by instance ID in the trigger so that each ref can listen to its component's enabled property simultaneously. I'm closing this so I can submit a new pull request for the updated version soon.