【问题标题】:How to handle multiple key inputs under new Unity Input system 1.0.0如何在新的 Unity 输入系统 1.0.0 下处理多个键输入
【发布时间】:2020-09-05 06:05:23
【问题描述】:

我正在尝试学习新的 Unity 输入系统。在以前的 Unity 输入系统中,

if (Input.GetKeyDown("f"))
    //do something when key 'f' is pressed
if (Input.GetKeyDown("g"))
    //do something when key 'g' is pressed
if (Input.GetKeyDown("h"))
    //do something when key 'h' is pressed
if (Input.GetKeyDown("j"))
    //do something when key 'j' is pressed

会沿着 f,g,h,j 的按键执行任何定义的操作。

在新的 Unity 输入系统中,有 InputAction,我可以定义 Action Maps、Actions 和 Properties。然后我可以实现如下功能,可以在播放器对象的检查器下从 PlayerInput 调用。

public void OnKey_F(InputAction.CallbackContext context)
{
    if (context.started)
        Debug.Log("Pressed F");
}
public void OnKey_G(InputAction.CallbackContext context)
{
    if (context.started)
        Debug.Log("Pressed G");
}
public void OnKey_H(InputAction.CallbackContext context)
{
    if (context.started)
        Debug.Log("Pressed H");
}
public void OnKey_J(InputAction.CallbackContext context)
{
    if (context.started)
        Debug.Log("Pressed J");
}

在新的 Unity 输入系统下,这是执行与上述相同功能的正确方法吗?我找到的教程主要是针对 WASD 运动的,我已经弄清楚它是如何工作的(2d 矢量)。但是,我不确定这种情况是否需要多个键来实现多种功能。

【问题讨论】:

    标签: c# unity3d input user-input


    【解决方案1】:

    有几种方法可以做到这一点,所以很抱歉,我仍然不是 100% 使用此表单,但我想我会分享一个简单的实现,它可以通过多次按键来很好地为我工作,即完全绕过了大部分检查员的工作。

    首先选择 Player Input Map 资源并确认“生成 C# 类”按钮已激活并应用。

    然后在 MonoBehavior 脚本中,我们实例化该类,并添加内联回调函数:

    PlayerInputClass Inputs;
    
    void Awake(){
        Inputs = new PlayerInputClass();
        Inputs.Enable();
    
        // Examples. You can add as many as you want.
    
        // You can put the ContextCallback to use
        Inputs.Player.Move.performed += ctx => Movement = ctx.ReadValue<Vector2>();
    
        // You can complete ignore it
        Inputs.Player.Roll.performed += ctx => _RollInputFlag = true;
    
        // You can define a function to handle the press
        Inputs.Player.OtherAction.performed += FunctionThatRuns();
    }
    

    我通常会选择翻转标志,以便脚本可以准确决定何时响应并恢复标志。

    注意这里Player是动作映射名称,后面的名称是实际动作名称。这也很好,因为 Intellisense 会发挥作用并提供帮助。

    【讨论】:

      猜你喜欢
      • 2022-06-21
      • 2023-01-30
      • 1970-01-01
      • 2020-12-31
      • 2020-09-29
      • 2020-08-30
      • 2022-10-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多