using System; // require keep for Windows Universal App using UnityEngine; namespace UniRx.Triggers { public abstract class ObservableTriggerBase : MonoBehaviour { bool calledAwake = false; Subject awake; /// Awake is called when the script instance is being loaded. void Awake() { calledAwake = true; if (awake != null) { awake.OnNext(Unit.Default); awake.OnCompleted(); } } /// Awake is called when the script instance is being loaded. public IObservable AwakeAsObservable() { if (calledAwake) return Observable.Return(Unit.Default); return awake ?? (awake = new Subject()); } bool calledStart = false; Subject start; /// Start is called on the frame when a script is enabled just before any of the Update methods is called the first time. void Start() { calledStart = true; if (start != null) { start.OnNext(Unit.Default); start.OnCompleted(); } } /// Start is called on the frame when a script is enabled just before any of the Update methods is called the first time. public IObservable StartAsObservable() { if (calledStart) return Observable.Return(Unit.Default); return start ?? (start = new Subject()); } bool calledDestroy = false; Subject onDestroy; /// This function is called when the MonoBehaviour will be destroyed. void OnDestroy() { calledDestroy = true; if (onDestroy != null) { onDestroy.OnNext(Unit.Default); onDestroy.OnCompleted(); } RaiseOnCompletedOnDestroy(); } /// This function is called when the MonoBehaviour will be destroyed. public IObservable OnDestroyAsObservable() { if (this == null) return Observable.Return(Unit.Default); if (calledDestroy) return Observable.Return(Unit.Default); return onDestroy ?? (onDestroy = new Subject()); } protected abstract void RaiseOnCompletedOnDestroy(); } }