using System; using System.Reactive.Disposables; using UnityEngine; namespace Chernobyl.Unity.Event { /// /// Forwards events from a to one from a /// collection and then moves to the next in that collection in /// preparation for the next event. /// public class EventCarousel : MonoBehaviour { /// /// When an event is received from this input, it will be sent through the current item from /// and then the next item will be selected. /// [Tooltip("When an event is received from this input, it will be sent through the current " + "item from Outputs and then the next item will be selected.")] public EventSource Input; /// /// The instances that are to receive events, one at a time. /// [Tooltip("The EventSources that are to receive events, one at a time.")] public EventSource[] Outputs = Array.Empty(); /// See Unity docs for more info. public void Start() { Input.ThrowIfNull(nameof(Input)); Outputs.ThrowIfEmptyOrNull(nameof(Outputs)); } /// See Unity docs for more info. public void OnEnable() => _subscription = Input.Observable.Subscribe(OnNext); /// See Unity docs for more info. public void OnDisable() => _subscription.Dispose(); /// See Unity docs for more info. public void OnDestroy() => _subscription.Dispose(); void OnNext(object obj) { Outputs[_currentOutputIndex].Subject.OnNext(obj); _currentOutputIndex++; if (_currentOutputIndex >= Outputs.Length) _currentOutputIndex = 0; } IDisposable _subscription = Disposable.Empty; int _currentOutputIndex; } }