77 lines
2.3 KiB
C#
77 lines
2.3 KiB
C#
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
|
|
namespace LLM.Commands
|
|
{
|
|
public class LLMCommandRouter : MonoBehaviour
|
|
{
|
|
[Header("Registry")]
|
|
[SerializeField] private bool autoDiscoverReceiversOnAwake = true;
|
|
[SerializeField] private List<LLMCommandReceiverBase> receivers = new List<LLMCommandReceiverBase>();
|
|
|
|
[Header("Debug")]
|
|
[SerializeField] private bool debugLogs = true;
|
|
|
|
private readonly Dictionary<string, LLMCommandReceiverBase> map = new Dictionary<string, LLMCommandReceiverBase>();
|
|
|
|
private void Awake()
|
|
{
|
|
if (autoDiscoverReceiversOnAwake)
|
|
{
|
|
AutoDiscoverReceivers();
|
|
}
|
|
|
|
RebuildMap();
|
|
}
|
|
|
|
public void AutoDiscoverReceivers()
|
|
{
|
|
receivers.Clear();
|
|
receivers.AddRange(FindObjectsOfType<LLMCommandReceiverBase>(true));
|
|
}
|
|
|
|
public void RebuildMap()
|
|
{
|
|
map.Clear();
|
|
|
|
for (int i = 0; i < receivers.Count; i++)
|
|
{
|
|
var r = receivers[i];
|
|
if (r == null) continue;
|
|
if (string.IsNullOrWhiteSpace(r.TargetId)) continue;
|
|
|
|
if (map.ContainsKey(r.TargetId))
|
|
{
|
|
if (debugLogs) Debug.LogWarning($"[LLMCommandRouter] Duplicate targetId='{r.TargetId}'.", r);
|
|
continue;
|
|
}
|
|
|
|
map.Add(r.TargetId, r);
|
|
}
|
|
|
|
if (debugLogs) Debug.Log($"[LLMCommandRouter] Registry built. targets={map.Count}", this);
|
|
}
|
|
|
|
public int ExecuteAll(LLMCommand[] commands)
|
|
{
|
|
if (commands == null || commands.Length == 0) return 0;
|
|
|
|
int executed = 0;
|
|
for (int i = 0; i < commands.Length; i++)
|
|
{
|
|
var cmd = commands[i];
|
|
if (cmd == null) continue;
|
|
if (string.IsNullOrWhiteSpace(cmd.targetId)) continue;
|
|
|
|
if (!map.TryGetValue(cmd.targetId, out var receiver) || receiver == null) continue;
|
|
|
|
if (receiver.TryExecute(cmd)) executed++;
|
|
}
|
|
|
|
if (debugLogs) Debug.Log($"[LLMCommandRouter] Executed commands={executed}/{commands.Length}", this);
|
|
return executed;
|
|
}
|
|
}
|
|
}
|
|
|