// Copyright (c) 2015 - 2023 Doozy Entertainment. All Rights Reserved. // This code can only be used under the standard Unity Asset Store End User License Agreement // A Copy of the EULA APPENDIX 1 is available at http://unity3d.com/company/legal/as_terms using System; using Doozy.Runtime.Signals; using UnityEngine; using UnityEngine.Events; namespace Doozy.Runtime.Mody { /// /// Base class for actions, that have a value, in the Mody System. /// Any action with a value that interacts with the system needs to derive from this. /// It is used to start, stop and finish Module's (MonoBehaviour's) tasks. /// It can be triggered manually (via code) or by any Trigger registered to the system. /// /// Value type [Serializable] public abstract class MetaModyAction : ModyAction { /// ModyAction's value public T ActionValue; /// Callback triggered by this ModyAction public UnityAction actionCallback { get; private set; } /// Construct a new with the given settings /// MonoBehaviour the ModyAction belongs to /// Name of the action /// Callback triggered by the ModyAction protected MetaModyAction(MonoBehaviour behaviour, string actionName, UnityAction callback) : base(behaviour, actionName) { actionCallback = callback; HasValue = true; ValueType = typeof(T); IgnoreSignalValue = false; ReactToAnySignal = false; } protected override void Run(Signal signal) { if (ReactToAnySignal) { if (IgnoreSignalValue) { actionCallback?.Invoke(ActionValue); //invoke callbacks return; } //do not react to any signal --> check for valid signal to update the value if (signal != null && signal.valueType == ValueType) ActionValue = signal.GetValueUnsafe(); //get value from signal actionCallback?.Invoke(ActionValue); //invoke callbacks return; } //do not react to any signal --> check for valid signal if (signal == null) return; //signal is null --> return if (!signal.hasValue) return; //signal does not have value --> return if (signal.valueType != ValueType) return; //signal value type does not match the action value type --> return if (IgnoreSignalValue) { actionCallback?.Invoke(ActionValue); //invoke callbacks return; } ActionValue = signal.GetValueUnsafe(); //get value from signal actionCallback?.Invoke(ActionValue); //invoke callbacks } /// Set a new value to the ModyAction /// New value public void SetValue(T value) => ActionValue = value; /// Set a new value to the ModyAction as an object /// New value as an object /// True if the operation was a success and false otherwise public override bool SetValue(object objectValue) => SetValue(objectValue, true); internal override bool SetValue(object objectValue, bool restrictValueType) { if (objectValue == null) return false; if (restrictValueType && objectValue.GetType() != ValueType) return false; try { SetValue((T)objectValue); return true; } catch { // ignored return false; } } } }