Adam Ramberg 7bdb2b7cf2
Trigger initial events for instancers (#220)
* - Trigger initial events for instancers
- Clean up event name for events instantiated at runtime
- Added properties to check if an event is set or not on a variable. This is useful in order to not accidentally create an event at runtime when just checking if it is null or not.
- Added logic to clean up events instantiated at runtime.

* Added an explicit GetOrCreateEvent method
2020-12-26 19:52:37 +01:00

86 lines
3.1 KiB
C#

using System;
using UnityEngine;
namespace UnityAtoms
{
/// <summary>
/// An Event Reference lets you define an event in your script where you then from the inspector can choose if it's going to use the Event from an Event, Event Instancer, Variable or a Variable Instancer.
/// </summary>
/// <typeparam name="T">The type of the event.</typeparam>
/// <typeparam name="V">Variable of type `T`.</typeparam>
/// <typeparam name="E">Event of type `T`.</typeparam>
/// <typeparam name="VI">Variable Instancer of type `T`.</typeparam>
/// <typeparam name="EI">Event Instancer of type `T`.</typeparam>
public abstract class AtomEventReference<T, V, E, VI, EI> : AtomBaseEventReference<T, E, EI>, IGetEvent, ISetEvent
where V : IGetOrCreateEvent, ISetEvent
where E : AtomEvent<T>
where VI : IGetOrCreateEvent, ISetEvent
where EI : AtomEventInstancer<T, E>
{
/// <summary>
/// Get or set the Event used by the Event Reference.
/// </summary>
/// <value>The event of type `E`.</value>
public override E Event
{
get
{
switch (_usage)
{
case (AtomEventReferenceUsage.VARIABLE): return _variable.GetOrCreateEvent<E>();
case (AtomEventReferenceUsage.VARIABLE_INSTANCER): return _variableInstancer.GetOrCreateEvent<E>();
case (AtomEventReferenceUsage.EVENT_INSTANCER): return _eventInstancer.Event;
case (AtomEventReferenceUsage.EVENT):
default:
return _event;
}
}
set
{
switch (_usage)
{
case (AtomEventReferenceUsage.VARIABLE):
{
_variable.SetEvent<E>(value);
break;
}
case (AtomEventReferenceUsage.VARIABLE_INSTANCER):
{
_variableInstancer.SetEvent<E>(value);
break;
}
case (AtomEventReferenceUsage.EVENT):
{
_event = value;
break;
}
default:
throw new NotSupportedException($"Event not reassignable for usage {_usage}.");
}
}
}
/// <summary>
/// Variable used if `Usage` is set to `Variable`.
/// </summary>
[SerializeField]
private V _variable = default(V);
/// <summary>
/// Variable Instancer used if `Usage` is set to `VariableInstancer`.
/// </summary>
[SerializeField]
private VI _variableInstancer = default(VI);
protected AtomEventReference()
{
_usage = AtomEventReferenceUsage.EVENT;
}
public static implicit operator E(AtomEventReference<T, V, E, VI, EI> reference)
{
return reference.Event;
}
}
}