using System.Collections; using System.Collections.Generic; using System.Reflection; using System.Linq; using Cysharp.Threading.Tasks; using System.Text; using System.Threading.Tasks; namespace BITKit { public static class BITCommand { [BITCommand] public static void Help() { StringBuilder sb = new StringBuilder(); sb.AppendLine("----------Commands--------"); methodInfos.ForEach(x => { StringBuilder stringBuilder = new(); StringBuilder samplesBuilder=new StringBuilder(); stringBuilder.Append(x.Value.Name); stringBuilder.Append('('); foreach (var parmeter in x.Value.GetParameters()) { stringBuilder.Append($"{parmeter.ParameterType.Name} {parmeter.Name}"); samplesBuilder.Append(parmeter.Name); } stringBuilder.Append(");"); sb.AppendLine($"{stringBuilder} \t// {x.Value.Name} {samplesBuilder}"); }); sb.AppendLine("----------End--------"); BIT4Log.Log(sb); } [BITCommand] public static void Error(string value) { BIT4Log.Log(value); } [BITCommand] public static void Warning(string value) { BIT4Log.Warnning(value); } [BITCommand] public static async void Quit() { await BITApp.Stop(); } public static IEnumerable GetMethodInfos(string keyWord) { return methodInfos.Where(x => x.Key.Contains(keyWord)).Select(x => x.Value); } public static async void Excute(string cmd) { await UniTask.SwitchToThreadPool(); await TaskHelper.WaitUntil(() => state is InitializationState.Initialized); var split = cmd.Split(" ").ToList(); var args = split.GetRange(1, split.Count - 1); cmd = split.First().ToLower(); if (methodInfos.TryGetValue(cmd, out var methodInfo)) { var parameterInfos = methodInfo.GetParameters(); var parameters = new List(); parameterInfos.ForEach((i, x) => { var arg = args[i]; object parameter = arg; if (x.ParameterType == typeof(int)) { parameter = int.Parse(arg); } else if (x.ParameterType == typeof(float)) { parameter = float.Parse(arg); } parameters.Add(parameter); }); //await UniTask.SwitchToMainThread(); methodInfo.Invoke(null, parameters.ToArray()); } else { BIT4Log.Log($"没有找到命令:{cmd}"); } } static Dictionary methodInfos = new(); static InitializationState state; [ExcuteOnStart] public static void Start() { try { Init(); } catch (System.Exception e) { BIT4Log.LogException(e); } } [ExcuteOnStop] public static void Stop() { state = 0; methodInfos.Clear(); } static async void Init() { state = InitializationState.Initializing; await UniTask.SwitchToThreadPool(); Data.AddListener("Cmd", Excute); Data.AddListener("cmd", Excute); Data.AddListener("command", Excute); Data.AddListener("Command", Excute); methodInfos.Clear(); var commands = (await ReflectionHelper.GetMethods()) .Where(x => x.IsStatic) .Where(x => x.GetCustomAttribute() is not null); foreach (var command in commands) { try { methodInfos.Add(command.Name.ToLower(), command); } catch (System.Exception e) { BIT4Log.LogException(e); } } state = InitializationState.Initialized; } } }