This repository has been archived by the owner on Feb 16, 2024. It is now read-only.
Upgrade ObservableEnableTrigger to handle multiple MonoBehaviours #466
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
I fixed two things in the ObservableEnableTrigger class:
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.
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.