diff --git a/MovementDefinitionApplier.cs b/MovementDefinitionApplier.cs new file mode 100644 index 0000000..b52ea6b --- /dev/null +++ b/MovementDefinitionApplier.cs @@ -0,0 +1,73 @@ +using System; +using Syntriax.Modules.Movement.Config; +using UnityEngine; + +namespace Syntriax.Modules.Movement +{ + public class MovementDefinitionApplier : MonoBehaviour + { + [Tooltip("The definition's name as defined in it's \"Name\" field")] + [SerializeField] private string startupDefinitionName = ""; + + private string appliedDefinitionName = ""; + public Action OnMovementDefinitionApplied = null; + public Action OnMovementDefinitionRemoved = null; + + private void Awake() + { + if (string.IsNullOrWhiteSpace(startupDefinitionName)) + return; + + LoadDefinition(startupDefinitionName); + } + + public void LoadDefinition(string definitionName) + { + RemoveDefinition(); + + MovementDefinitionFactory.Instance.ApplyDefinitionToGameObject(gameObject, definitionName); + appliedDefinitionName = definitionName; + OnMovementDefinitionApplied?.Invoke(gameObject); + } + + public void LoadDefinition(MovementDefinition definition) + { + RemoveDefinition(); + + MovementDefinitionFactory.Instance.ApplyDefinitionToGameObject(gameObject, definition); + appliedDefinitionName = definition.Name; + OnMovementDefinitionApplied?.Invoke(gameObject); + } + + public void RemoveDefinition() + { + if (string.IsNullOrWhiteSpace(appliedDefinitionName)) + return; + + MovementDefinition appliedDefinition = MovementDefinitionFactory.Instance.Definitions[appliedDefinitionName]; + if (appliedDefinition.MovementConfigs == null || appliedDefinition.MonoBehaviours == null) + return; + + foreach (MovementConfig movementConfig in appliedDefinition.MovementConfigs) + { + Type type = MovementFactory.Instance.Types[movementConfig.TypeName]; + if (TryGetComponent(type, out Component component)) + Destroy(component); + } + + foreach (string monoBehaviour in appliedDefinition.MonoBehaviours) + { + Type type = MovementFactory.Instance.Types[monoBehaviour]; + if (TryGetComponent(type, out Component component)) + Destroy(component); + } + + appliedDefinition = default; + OnMovementDefinitionRemoved?.Invoke(gameObject); + } + + [ContextMenu("Load Longer")] private void LoadLonger() => LoadDefinition("Example Movement Definition (Longer)"); + [ContextMenu("Load Quick")] private void LoadQuick() => LoadDefinition("Example Movement Definition (Quick)"); + [ContextMenu("Remove Definition")] private void UnloadDefinition() => RemoveDefinition(); + } +} diff --git a/MovementDefinitionApplier.cs.meta b/MovementDefinitionApplier.cs.meta new file mode 100644 index 0000000..c495168 --- /dev/null +++ b/MovementDefinitionApplier.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 9b796cc8b20771c47bfed932ebf7d685 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: