com.alicizax.unity.ui.exten.../Runtime/UXComponent/Controller/UXControllerStateRecorder.cs

113 lines
2.8 KiB
C#

using System;
using System.Collections.Generic;
using UnityEngine;
namespace AlicizaX.UI
{
[DisallowMultipleComponent]
[AddComponentMenu("UX/UX Controller State Recorder")]
public class UXControllerStateRecorder : MonoBehaviour
{
[SerializeField] private int _id;
[SerializeField] private UXController _controller;
internal int ID => _id;
internal UXController Controller => _controller;
[Serializable]
public class StateEntry
{
[SerializeReference] public ControllerStateBase State = null;
public string ControllerName = string.Empty;
public int ControllerIndex = 0;
}
[SerializeField] private List<StateEntry> _stateEntries = new List<StateEntry>();
internal List<StateEntry> StateEntries => _stateEntries;
private bool _initialized = false;
#region Unity Lifecycle
private void Awake()
{
Initialize();
}
private void OnDestroy()
{
if (_controller != null)
{
_controller.UnregisterRecorder(this);
}
}
#endregion
#region Public API
public void Initialize()
{
if (_initialized) return;
_initialized = true;
foreach (var entry in _stateEntries)
{
if (entry?.State != null)
{
entry.State.Init(this);
}
}
}
public void SetController(UXController controller)
{
if (_controller != null)
{
_controller.UnregisterRecorder(this);
}
_controller = controller;
if (_controller != null)
{
_controller.RegisterRecorder(this);
}
}
#endregion
#region Internal API
internal void OnControllerIndexChanged(string controllerName, int selectedIndex)
{
for (int i = 0; i < _stateEntries.Count; i++)
{
var entry = _stateEntries[i];
if (entry != null && entry.ControllerName == controllerName && entry.State != null)
{
try
{
entry.State.Execute(this, entry.ControllerIndex, selectedIndex);
}
catch (Exception ex)
{
Debug.LogError($"Error executing state {entry.State.GetType().Name}: {ex.Message}", this);
}
}
}
}
internal void GenerateID()
{
if (_id <= 0)
{
_id = UnityEngine.Random.Range(10000000, 99999999);
}
}
#endregion
}
}