我目前正在嘗試為我的游戲制作一個控制臺,并決定制作一個Command可以用來輕松創建命令的類是一個好主意。我創建了這個類,但當然這些類會做完全不同的事情,因此我正在考慮創建一個基本上可以像函式一樣作業的屬性,也就是我可以構造一個帶有屬性commandName、引數和可自定義代碼塊的命令然后將在撰寫命令時執行。我該怎么辦?
public class Command : MonoBehaviour
{
string inputCommand;
int arguments;
void execution()
{
//this is where to codeblock to be executed upon typing the command would go
}
}
編輯:我取得了似乎取得進展但似乎仍然無法做到的事情。此外,每個動作都需要能夠有不同數量的引數(例如“runes.add”需要一個整數來添加符文,而“updatestore”不需要)。任何幫助將不勝感激
public class Command : MonoBehaviour
{
public string InputCommand { get; set; }
public int Arguments { get; set; }
public Action ExecuteAction { get; set; }
}
public class Commands
{
public List<Command> commandCollection = new List<Command>()
{
new Command()
{
InputCommand = "",
Arguments = 1,
ExecuteAction = new Action(()=>{code to execute goes here})
}
};
}
uj5u.com熱心網友回復:
首先,如果要使用物件建構式(而不是實體化)構造 Command,則不應從 MonoBehaviour 派生 Command。
我認為您應該創建抽象 Command 類并將命令創建為從 Command 類派生的類。
您所謂的“代碼塊”也可以使用多型性來完成。
所以,你需要做的是:
- 創建命令類
public abstract class Command
{
public abstract void Execute(string[] args);
}
Execute 方法是抽象的,因此我們可以在子類中覆寫該方法的實作。此方法將命令引數陣列作為引數。
- 創建一些測驗命令
public class TestCommand : Command
{
public override void Execute(string[] args)
{
Debug.Log("Test command invoked, passed parameters count: " args.Length);
}
}
- 創建 CommandRegistry 類(這是你的 Commands 類)
public class CommandRegistry
{
private Dictionary<string, Command> _commands;
public CommandRegistry()
{
_commands = new Dictionary<string, Command>();
}
public void RegisterCommand(string name, Command command)
{
// You should also check here if command already exists
if(_commands.ContainsKey(name))
{
// Print error here or throw an exception
return;
}
_commands[name] = command;
}
public void RegisterAllCommands()
{
// Add here every new command to register it
RegisterCommand("test", new TestCommand());
}
// Returns false if command not found
public bool ExecuteCommand(string commandName, string[] args)
{
if(_commands.ContainsKey(commandName) == false)
return false;
_commands[commandName].Execute(args);
return true;
}
}
而已。您需要呼叫 ExecuteCommand 方法來執行命令并傳遞命令的名稱和引數。
您應該檢查 Command.Execute 方法中的引數計數。
此外,如果您需要訪問您的游戲方法/欄位(例如添加符文),您應該提供對此欄位/方法的靜態訪問或創建類似 CommandContext 類(或 GameContext)的內容。
這個類的一個實體將被傳遞給每個命令,它包含對可以執行諸如添加符文之類的物件的參考。
然后您需要向 GameRegistry.ExecuteCommand 和 Command.Execute 方法添加一個新引數 (CommandContext)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/483843.html
下一篇:初始值n自定義編輯器
