【发布时间】:2020-04-18 08:42:03
【问题描述】:
我正在尝试为 Unity 游戏的简单通用输入/控制器系统找出一个好的设计模式,该系统可用于玩家、NPC、车辆等。我当前的设计使用一个控制器超类,它具有“Actions”的静态数组,每个都有关于如何触发“Action States”数组中的相应布尔值、键绑定等的基本信息。然后我可以为特定控制器指定派生类。我对这个设计的实现如下所示。
控制器超类:
public class Controller : MonoBehaviour
{
public class Action
{
public enum ActionType
{
Impulse,
Hold,
Toggle
};
public string name;
public ActionType actionType;
public KeyCode binding;
...
}
[HideInInspector]
public static Action[] actions;
public bool[] actionStates;
}
特定控制器示例:
public class HumanController : Controller
{
public bool sprint { get { return actionStates[0]; } set { actionStates[0] = value; } }
public bool jump { get { return actionStates[1]; } set { actionStates[1] = value; } }
...
public bool openInventory { get { return actionStates[13]; } set { actionStates[13] = value; } }
public HumanController()
{
actions = new Action[]
{
new Action("Sprint", Action.InputType.Hold, KeyCode.LeftShift),
new Action("Jump", Action.InputType.Impulse, KeyCode.Space),
...
new Action("Open Inventory", Action.InputType.Toggle, KeyCode.Tab),
};
actionStates = new bool[actions.Length];
}
}
这个系统工作得很好,因为我可以在检查器中轻松查看 actionStates 数组,可以通过属性在代码中轻松访问它们,而不是使用字符串索引字典(我怀疑这会更慢并产生更多垃圾)等。唯一不理想的部分是手动设置属性,我想知道是否有一种更简洁/更优雅的方式将派生类中的每个属性映射到 actionStates 数组的每个元素而不是为每个操作执行以下操作:
public bool action { get { return actionStates [0]; } set { actionStates[0] = value; } }
【问题讨论】:
-
当心 Action 已经定义,因此可能会给您带来无法解释的行为或稍后阻止预期的行为。当然最好将带有枚举的数组作为计数器,所以 myAction[JUMP] = 。 ..等
标签: c# arrays unity3d properties