State/Runtime/Enable/StateEnableMonoBehaviour.cs

37 lines
959 B
C#

using System;
using UnityEngine;
namespace Syntriax.Modules.State
{
public class StateEnableMonoBehaviour : MonoBehaviour, IStateEnable
{
private bool _isEnabled = true;
public bool IsEnabled
{
get => _isEnabled;
set
{
if (value == _isEnabled)
return;
_isEnabled = value;
OnEnabledChanged?.Invoke(value);
}
}
public Action<bool> OnEnabledChanged { get; set; } = null;
protected void Awake()
=> OnEnabledChanged += (state) => enabled = state;
protected void OnEnable() => IsEnabled = true;
protected void OnDisable()
{
IsEnabled = false;
if (!gameObject.activeInHierarchy) // Just so we can get OnEnable called when the object is back active again in the hierarchy
this.enabled = true;
}
}
}