using System; using System.Linq; using SLSFramework.General; using UniRx; using UnityEngine; using UnityEngine.Events; namespace Continentis.MainGame.Commands { public class Cmd_Function : CommandBase { private readonly float functionDuration; private readonly UnityAction function; private readonly bool executeAtStart; public Cmd_Function(float functionDuration, UnityAction function, bool executeAtStart = true) : base(null) { this.functionDuration = functionDuration; this.function = function; this.executeAtStart = executeAtStart; } public Cmd_Function(UnityAction function) : base(null) { this.functionDuration = 0; this.function = function; this.executeAtStart = true; } protected override IObservable OnExecute(CommandContext outerContext) { if (functionDuration > 0) { if (executeAtStart) //在持续时间开始时执行 { function?.Invoke(); return Observable.Timer(TimeSpan.FromSeconds(functionDuration)).AsUnitObservable(); } return Observable.Timer(TimeSpan.FromSeconds(functionDuration)) .Do(_ => function?.Invoke()) .AsUnitObservable(); //在持续时间结束时执行 } function?.Invoke(); return Observable.Return(Unit.Default); //如果持续时间为0,立即完成 } } public class Cmd_ParamFunction : CommandBase where T : class { private readonly float functionDuration; private readonly UnityAction function; private readonly bool executeAtStart; public Cmd_ParamFunction(UnityAction function, CommandContext selfContext = null, bool executeAtStart = true) :base(selfContext) { this.functionDuration = 0; this.function = function; this.executeAtStart = executeAtStart; } public Cmd_ParamFunction(float functionDuration, UnityAction function, CommandContext selfContext = null, bool executeAtStart = true) :base(selfContext) { this.functionDuration = functionDuration; this.function = function; this.executeAtStart = executeAtStart; } protected override IObservable OnExecute(CommandContext outerContext) { if (selfContext.context.Count != 1) { Debug.LogWarning("Cmd_Function 期望 selfContext 只包含一个参数,作为 function 的输入。"); } T param = selfContext.context["Target"] as T; if (param == null) { Debug.LogWarning("Cmd_Function 未能从 selfContext 中获取到有效的参数。"); } if (functionDuration > 0) { if (executeAtStart) //在持续时间开始时执行 { function?.Invoke(param); return Observable.Timer(TimeSpan.FromSeconds(functionDuration)).AsUnitObservable(); } return Observable.Timer(TimeSpan.FromSeconds(functionDuration)) .Do(_ => function?.Invoke(param)) .AsUnitObservable(); //在持续时间结束时执行 } function?.Invoke(param); return Observable.Return(Unit.Default); //如果持续时间为0,立即完成 } } }