using System;
using UnityEngine;
using UnityEngine.Assertions;
namespace UnityAtoms
{
///
/// An Event Instancer is a MonoBehaviour that takes an Event as a base and creates an in memory copy of it on OnEnable.
/// This is handy when you want to use Events for prefabs that are instantiated at runtime.
///
/// The value type.
/// Event of type T.
[EditorIcon("atom-icon-sign-blue")]
[DefaultExecutionOrder(Runtime.ExecutionOrder.VARIABLE_INSTANCER)]
public abstract class AtomEventInstancer : MonoBehaviour, IGetEvent, ISetEvent
where E : AtomEvent
{
public T InspectorRaiseValue { get => _inspectorRaiseValue; }
///
/// Getter for retrieving the in memory runtime Event.
///
public E Event { get => _inMemoryCopy; }
[SerializeField]
[ReadOnly]
private E _inMemoryCopy;
///
/// The Event that the in memory copy will be based on when created at runtime.
///
[SerializeField]
private E _base = null;
///
/// Used when raising values from the inspector for debugging purposes.
///
[SerializeField]
[Tooltip("Value that will be used when using the Raise button in the editor inspector.")]
private T _inspectorRaiseValue = default(T);
private void OnEnable()
{
if (_base == null)
{
_inMemoryCopy = ScriptableObject.CreateInstance();
}
else
{
_inMemoryCopy = Instantiate(_base);
}
}
///
/// Get event by type.
///
///
/// The event.
public EO GetEvent() where EO : AtomEventBase
{
if (typeof(EO) == typeof(E))
return (Event as EO);
throw new Exception($"Event type {typeof(EO)} not supported! Use {typeof(E)}.");
}
///
/// Set event by type.
///
/// The new event value.
///
public void SetEvent(EO e) where EO : AtomEventBase
{
throw new Exception($"Event type not reassignable!");
}
///
/// Raises the instanced Event.
///
public void Raise()
{
Event.Raise();
}
///
/// Raises the instanced Event.
///
/// The value associated with the Event.
public void Raise(T item)
{
Event.Raise(item);
}
}
}