Unity新的Input System

参考:https://www.youtube.com/watch?v=HmXU4dZbaMw&ab_channel=BMo
参考:https://docs.unity3d.com/Packages/[email protected]/manual/index.html

Unity更新了新的Input System,让人比较烦的是,新的Input System与旧的Input System不可以存在,这篇文章主要是研究研究新系统应该怎么写。


整体介绍

新的Input系统并没有默认提供在Unity里,而是存在了对应的Package里,在UnityEngine.Input命名空间里,Package Manager里即可安装Input System插件,然后需要把项目设置从旧的Input系统修改为新的:

在这里插入图片描述


Quick start guide

老版的Unity Input系统,都是通过这种写法来获取Input的状态的

if (Input.GetKey(KeyCode.A)) ...
if (Input.GetAxis("Mouse X")) ...

而新的Input系统,可以有多种方式来获取Input:

  • 可以直接从Input Device里查询
  • 可以通过Input Action来获取,这种方法要稍微麻烦一点

从Input Device里查询

其实与老版的Input系统类似,比如:

using UnityEngine;
using UnityEngine.InputSystem;

public class MyPlayerScript : MonoBehaviour
{
    
    
    void Update()
    {
    
    
    	// 发现没, 这里的Input系统, 根据设备不同, 代码也不同
        var gamepad = Gamepad.current;
        if (gamepad == null)
            return; // No gamepad connected.

        if (gamepad.rightTrigger.wasPressedThisFrame)
        {
    
    
            // 'Use' code here
        }

        Vector2 move = gamepad.leftStick.ReadValue();
        // 'Move' code here
    }
}

The same approach works for other Device types (for example, Keyboard.current or Mouse.current),键鼠也是一样的,比如

    {
    
    
        // if (Keyboard.current.wKey.wasPressedThisFrame)// 短按
        if (Keyboard.current.wKey.isPressed)// 长按
        //if (Input.GetKey(KeyCode.W))		// 老的写法

从Input Action里查询

具体要分为三步:

  • 添加PlayerInput component
  • 创建Actions
  • 脚本里处理Action的responses

上面说的第一种方法,如果有人用键鼠、有人用手柄,那么他们的代码逻辑是不一样的,感觉比较麻烦。UE里就有Input Actions和Input Axis来处理这个映射关系,如下图所示:
在这里插入图片描述
Unity的也差不多,不过它相关设置没有写在Project Settings里(毕竟新Input系统也不是个Unity内置的东西),而是写在了Player Input组件上:
在这里插入图片描述
所以说,用的时候,给要接受Input的对象,加个这个组件,再点击Create Actions,不过创建Action的方式不止这一种,应该可以脚本里创建:
在这里插入图片描述
Unity会创建一个.inputactions资产,记录这个信息,可以在里面编辑不同设备对应的相同Actions。

最后,需要脚本里处理Action的responses(Setting up Action responses),每一个创建的Action都需要添加对应的回调,一共有四种方法,如下所示:
在这里插入图片描述
这里面可以拖拽对应的C#脚本,然后选择里面创建好的函数,像这样:
在这里插入图片描述
脚本里需要写与下面这种类似的函数:

public class MyPlayerScript : MonoBehaviour
{
    
    
    public void Fire(InputAction.CallbackContext context)
    {
    
    
        Debug.Log("Fire!");
    }
}

猜你喜欢

转载自blog.csdn.net/alexhu2010q/article/details/126146394
今日推荐