using System;
using System.Collections.Generic;
using UnityEngine;
namespace UnityAtoms
{
///
/// None generic base class for Events. Inherits from `BaseAtom` and `ISerializationCallbackReceiver`.
///
[EditorIcon("atom-icon-cherry")]
public abstract class AtomEventBase : BaseAtom, ISerializationCallbackReceiver, ITryGetOrCreateEvent, ITryGetEvent
{
///
/// Event without value.
///
public event Action OnEventNoValue;
public virtual void Raise()
{
#if !UNITY_ATOMS_GENERATE_DOCS && UNITY_EDITOR
StackTraces.AddStackTrace(GetInstanceID(), StackTraceEntry.Create());
#endif
OnEventNoValue?.Invoke();
}
///
/// Register handler to be called when the Event triggers.
///
/// The handler.
public void Register(Action del)
{
OnEventNoValue += del;
}
///
/// Unregister handler that was registered using the `Register` method.
///
/// The handler.
public void Unregister(Action del)
{
OnEventNoValue -= del;
}
///
/// Unregister all handlers that were registered using the `Register` method.
///
public virtual void UnregisterAll()
{
OnEventNoValue = null;
}
///
/// Register a Listener that in turn trigger all its associated handlers when the Event triggers.
///
/// The Listener to register.
public void RegisterListener(IAtomListener listener)
{
OnEventNoValue += listener.OnEventRaised;
}
///
/// Unregister a listener that was registered using the `RegisterListener` method.
///
/// The Listener to unregister.
public void UnregisterListener(IAtomListener listener)
{
OnEventNoValue -= listener.OnEventRaised;
}
public void OnBeforeSerialize() { }
public virtual void OnAfterDeserialize()
{
// Clear all delegates when exiting play mode
if (OnEventNoValue != null)
{
foreach (var d in OnEventNoValue.GetInvocationList())
{
OnEventNoValue -= (Action)d;
}
}
}
///
/// Contrary to the name, a new event is never created as it makes no sense (this is already an event class).
/// It is used for compatibility with the `ITryGetOrCreateEvent` interface.
///
public bool TryGetOrCreateEvent(out E atomEvent) where E : AtomEventBase
{
if (typeof(E).IsAssignableFrom(this.GetType()))
{
atomEvent = (E)this;
return true;
}
atomEvent = null;
return false;
}
public bool TryGetEvent(out E atomEvent) where E : AtomEventBase
{
if (typeof(E).IsAssignableFrom(this.GetType()))
{
atomEvent = (E)this;
return true;
}
atomEvent = null;
return false;
}
}
}