Unity下简易字符串指令调试
输入相应的字符串命令即可调用特定的方法,比如让角色等级提升,生成特定数量的Boss等
using System;
using UnityEngine;
using System.Collections.Generic;
using System.Reflection;
using UnityEditor;
public class GMEditor : EditorWindow
{
public string Input;
[MenuItem("Tools/GMCmd")]
static void ShowWindow()
{
GetWindow(typeof(GMEditor));
}
void OnGUI()
{
Input = GUILayout.TextField(Input, GUILayout.Height(30), GUILayout.Width(200));
if (GUILayout.Button("Submit", GUILayout.Width(100), GUILayout.Height(30)))
{
Debug.Log(GMModule.Instance.Call(Input));
}
}
}
/// <summary>
/// 指令管理模块
/// </summary>
public class GMModule
{
private static GMModule _instance;
//单例
public static GMModule Instance
{
get
{
if (_instance == null)
{
_instance = new GMModule();
_instance.Init();
}
return _instance;
}
}
/// <summary>
/// 存储命令及对应存储方法的字典
/// </summary>
private Dictionary<string, MethodInfo> m_methods = new Dictionary<string, MethodInfo>();
#region Public Methods
public void Init()
{
m_methods.Clear();
var type = typeof(GMModule);
var methods = type.GetMethods();
foreach (var each in methods)
{
var attribute = each.GetCustomAttributes(typeof(GMCommondAttribute), false);
if (attribute != null && attribute.Length > 0)
{
GMCommondAttribute gmc = attribute[0] as GMCommondAttribute;
m_methods.Add(gmc.Cmd.ToLower(), each);
}
}
}
/// <summary>
/// 执行指令
/// </summary>
public string Call(string input)
{
var tmpStr = input.ToLower().Split(' ');
var cmdStr = tmpStr[0];
if (m_methods.ContainsKey(cmdStr))
{
List<string> param = new List<string>();
for (int i = 1; i < tmpStr.Length; ++i)
{
param.Add(tmpStr[i]);
}
var method = m_methods[cmdStr];
var info = method.GetCustomAttributes(typeof(GMCommondAttribute), false)[0] as GMCommondAttribute;
if (param.Count != info.ParamNum)
{
return "Usage: " + info.Usage;
}
else
{
return m_methods[cmdStr].Invoke(this, new object[] { param.ToArray() }) as string;
}
}
else
{
return "Command Not Found!";
}
}
#region CmdMethod
[GMCommond("SpBoss", 2, "SpBoss 2 Dragon | 生成Boss")]
public string SpawnBoss(string[] args)
{
//logic to spawn Boos
return $"Spawn {int.Parse(args[0])} {args[1]}";
}
[GMCommond("userId", 0, "userId | 显示玩家ID")]
public string Help(string[] args)
{
int userId = 666;
//Query logic to get ID
return "User id is:" + userId;
}
[GMCommond("lvUp", 1, "lvUp 80 | 升级到xx ")]
public string LevelUp(string[] args)
{
//ask server to level up
return "level up to " + args[0];
}
#endregion
#endregion
}
/// <summary>
/// 指令特性,有字符串指令,参数个数,用例说明
/// </summary>
[AttributeUsage(AttributeTargets.Method)]
public class GMCommondAttribute : Attribute
{
public string Cmd;
public int ParamNum;
public string Usage;
public GMCommondAttribute(string cmd, int paramNum, string usage)
{
Cmd = cmd;
ParamNum = paramNum;
Usage = usage;
}
}
标签:return,methods,var,Unity,字符串,GMCommondAttribute,public,调试,string From: https://www.cnblogs.com/Firepad-magic/p/17145379.html有点像 字节码模式的简化版