Movement/Runtime/MovementDefinitionApplier.cs

75 lines
2.9 KiB
C#
Raw Permalink Normal View History

2022-11-18 12:07:44 +03:00
using System;
2022-11-21 13:51:55 +03:00
using Syntriax.Modules.Factory;
2022-11-18 12:07:44 +03:00
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<GameObject> OnMovementDefinitionApplied = null;
public Action<GameObject> OnMovementDefinitionRemoved = null;
private void Awake()
{
if (string.IsNullOrWhiteSpace(startupDefinitionName))
return;
LoadDefinition(startupDefinitionName);
}
public void LoadDefinition(string definitionName)
{
RemoveDefinition();
2022-11-21 13:51:55 +03:00
FactorySingleton<MovementDefinitionFactory>.Instance.ApplyDefinitionToGameObject(gameObject, definitionName);
2022-11-18 12:07:44 +03:00
appliedDefinitionName = definitionName;
OnMovementDefinitionApplied?.Invoke(gameObject);
}
public void LoadDefinition(MovementDefinition definition)
{
RemoveDefinition();
2022-11-21 13:51:55 +03:00
FactorySingleton<MovementDefinitionFactory>.Instance.ApplyDefinitionToGameObject(gameObject, definition);
2022-11-18 12:07:44 +03:00
appliedDefinitionName = definition.Name;
OnMovementDefinitionApplied?.Invoke(gameObject);
}
public void RemoveDefinition()
{
if (string.IsNullOrWhiteSpace(appliedDefinitionName))
return;
2022-11-21 13:51:55 +03:00
MovementDefinition appliedDefinition = FactorySingleton<MovementDefinitionFactory>.Instance.Definitions[appliedDefinitionName];
2022-11-18 12:07:44 +03:00
if (appliedDefinition.MovementConfigs == null || appliedDefinition.MonoBehaviours == null)
return;
foreach (MovementConfig movementConfig in appliedDefinition.MovementConfigs)
{
2022-11-21 13:51:55 +03:00
Type type = FactorySingleton<MovementFactory>.Instance.Types[movementConfig.TypeName];
2022-11-18 12:07:44 +03:00
if (TryGetComponent(type, out Component component))
Destroy(component);
}
foreach (string monoBehaviour in appliedDefinition.MonoBehaviours)
{
2022-11-21 13:51:55 +03:00
Type type = FactorySingleton<MovementFactory>.Instance.Types[monoBehaviour];
2022-11-18 12:07:44 +03:00
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();
}
}