using System;
using Chernobyl.Collections.Generic;
using Chernobyl.Destruction;
using UnityEngine;
namespace Chernobyl.Unity.Event
{
///
/// Toggles the enable state of an on and off based on events.
///
public class EnableToggle : MonoBehaviour
{
///
/// The event that causes the attached to object to be enabled.
///
[Tooltip("The event that causes the attached to object to be enabled.")]
public EventSource Enable;
///
/// The event that causes the attached to object to be disabled.
///
[Tooltip("The event that causes the attached to object to be disabled.")]
public EventSource Disable;
///
/// The instances that are to be toggled.
///
[Tooltip("The Behaviours that are to be toggled.")]
public Behaviour[] 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 " +
"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.enabled = true);
void OnEventDisable(object obj) => Toggleables.For(t => t.enabled = false);
IDisposable _enableSubscription = Disposable.Empty;
IDisposable _disableSubscription = Disposable.Empty;
}
}