using System; using Chernobyl.Collections.Generic; using Chernobyl.Destruction; using UnityEngine; namespace Chernobyl.Unity.Event { /// /// Toggles the active state of an on and off based on events. /// public class ActiveToggle : MonoBehaviour { /// /// The event that causes the attached to object to be active. /// [Tooltip("The event that causes the attached to object to be active.")] public EventSource Enable; /// /// The event that causes the attached to object to be inactive. /// [Tooltip("The event that causes the attached to object to be inactive.")] public EventSource Disable; /// /// The objects that are to be toggled. /// [Tooltip("The objects that are to be toggled.")] public GameObject[] Toggleables; /// See Unity docs for more info. public void Start() { if (Enable == null && Disable == null) throw new ArgumentNullException($"The {nameof(Enable)} and {nameof(Disable)} are " + "are null. At least one must be set."); Toggleables.ThrowIfEmptyOrNull(nameof(Toggleables)); if(Enable != null) _enableSubscription = Enable.Observable.Subscribe(OnEventEnable); if(Disable != null) _disableSubscription = Disable.Observable.Subscribe(OnEventDisable); } /// See Unity docs for more info. public void OnDestroy() { _enableSubscription.Dispose(); _disableSubscription.Dispose(); } void OnEventEnable(object obj) => Toggleables.For(t => t.SetActive(true)); void OnEventDisable(object obj) => Toggleables.For(t => t.SetActive(false)); IDisposable _enableSubscription = Disposable.Empty; IDisposable _disableSubscription = Disposable.Empty; } }