如何创建一个类与可定制的代码块?



我目前正试图为我的游戏制作一个主机,并决定制作一个名为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
}
}

编辑:我似乎取得了进步,但似乎还是做不对。此外,每个动作都需要能够拥有不同数量的参数(例如" runs .add")需要一个整数来添加符文和"更新存储";需要没有)。如有任何帮助,不胜感激

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})
}
};
}

首先,如果你想用对象构造函数(而不是实例化)构造Command,你不应该从MonoBehaviour派生Command。

我认为你应该创建抽象的Command类,并创建命令作为Command类的派生类。

也就是你们所说的"代码块"可以使用多态性完成。

那么,你需要做的是:

  1. 创建命令类
public abstract class Command
{
public abstract void Execute(string[] args);
}

Execute方法是抽象的,因此我们可以在子类中重写该方法的实现。这个方法接受一个命令参数数组作为参数。

  1. 创建一些测试命令
public class TestCommand : Command
{
public override void Execute(string[] args)
{
Debug.Log("Test command invoked, passed parameters count: " + args.Length);
}
}
  1. 创建CommandRegistry类(这是您的命令类)
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方法来执行命令,并传递命令的名称和参数。

您应该检查命令中的参数计数。执行方法。

如果你需要访问你的游戏方法/字段(例如添加符文),你应该提供对这些字段/方法的静态访问,或者创建类似CommandContext类(或GameContext)的东西。

这个类的一个实例将被传递给每个命令,它包含对对象的引用,这些对象可以做一些事情,比如添加符文。

然后你需要添加一个新的参数(CommandContext)到gamerregistry。ExecuteCommand和Command。执行方法。

最新更新