using System.Collections.Generic; using Opsive.BehaviorDesigner.Runtime.Tasks; using Opsive.GraphDesigner.Runtime; using Opsive.GraphDesigner.Runtime.Variables; using Opsive.Shared.Utility; using UnityEngine; namespace Cielonos.MainGame.Characters.AI { [Description("向指定的目标(或自身)派发一个上下文事件(ContextEvent),以便其行为树中的 HasReceivedContextEvent 节点能够响应。")] [NodeIcon("Assets/Sprites/Icon/Megaphone.png")] [Category("Cielonos/Events")] public class DispatchContextEvent : AutomataActionBase { [Tooltip("派发的目标列表。如果留空或未指定,则默认派发给 AI 自己。目标 GameObject 必须含有 BehaviorSubcontroller 组件。")] public List> targetList; [Tooltip("派发的事件名称")] public SharedVariable eventName; [Tooltip("(额外数据)参数1")] public SharedVariable arg1; [Tooltip("(额外数据)参数2")] public SharedVariable arg2; [Tooltip("(额外数据)参数3")] public SharedVariable arg3; public override TaskStatus OnUpdate() { if (eventName == null || string.IsNullOrEmpty(eventName.Value)) { Debug.LogWarning("[DispatchContextEvent] 未指定事件名称,派发失败。"); return TaskStatus.Failure; } object val1 = GetValueSafe(arg1); object val2 = GetValueSafe(arg2); object val3 = GetValueSafe(arg3); if (targetList != null && targetList.Count > 0) { // 发送给目标列表中的所有单位 foreach (SharedVariable targetGo in targetList) { if (targetGo != null) { var bSc = targetGo.Value.GetComponent(); if (bSc != null) { bSc.DispatchContextEvent(eventName.Value, val1, val2, val3); } else { // 尝试向其子节点的对象发送 var charBase = targetGo.Value.GetComponent(); if (charBase != null && charBase is Automata automata && automata.behaviorSc != null) { automata.behaviorSc.DispatchContextEvent(eventName.Value, val1, val2, val3); } } } } } else { // 列表为空,默认发给自己 if (behaviorSc != null) { behaviorSc.DispatchContextEvent(eventName.Value, val1, val2, val3); } } return TaskStatus.Success; } private object GetValueSafe(SharedVariable sharedVar) { return sharedVar?.GetValue() == null ? null : sharedVar.GetValue(); } public override void Reset() { base.Reset(); eventName = ""; targetList = null; arg1 = null; arg2 = null; arg3 = null; } } }