public static SubListeners <S> NewSubStateListenerForUnity <T, S>(this SubListeners <T> self, UnityEngine.Object context, Func <T, S> getSubState, bool eventsAlwaysInMainThread = true) { var subListener = new SubListeners <S>(getSubState(self.latestSubState)); var ownListenerInParent = self.AddStateChangeListener(getSubState, newSubState => { if (eventsAlwaysInMainThread) { MainThread.Invoke(() => { OnSubstateChangedForUnity(subListener, newSubState, context); }); } else { OnSubstateChangedForUnity(subListener, newSubState, context); } }); subListener.SetUnregisterInParentAction(() => { self.innerListeners -= ownListenerInParent; }); return(subListener); }
private static void OnSubstateChangedForUnity <V>(SubListeners <V> onStateChanged, V newVal, UnityEngine.Object context) { if (context.IsDestroyed()) { onStateChanged.UnregisterFromParent(); return; } if (context is Behaviour b && !b.isActiveAndEnabled) { return; } if (context is GameObject go && !go.activeInHierarchy) { return; } onStateChanged.OnSubstateChanged(newVal); }