InputSystem

  • 安装所需插件
  • 使用
  • 跳跃
  • 移动


安装所需插件

version 1.3.0
 Unity最初没有遇见到现在的多平台和多种多样的输入设备,最初的输入系统的设计很多需求难以满足所以推出了InputSystsem。
安装要求:
 Unity2019.4和.Net 4以上版本。
安装:
 直接到包管理器Window > Package Manager安装即可,安装后提示需要重启,重启后即可使用。
注意:
1、InputSystem与一部分Unity内置的功能尚不兼容,酌情使用,详情参考官方文档。
2、如果想要切换输入系统,可以到Edit > Project Settings > Player在Other Settings中可以选择两种输入方式中的任意一种使用,也可以同时使用。

unity的enter输入 unity输入系统_unity

使用

1、创建Input Actions组件

两种途径可以创建:
1、右键单击Create-->Input Actions创建

unity的enter输入 unity输入系统_unity的enter输入_02

2、在想要控制的物体上挂载组件Player Input后单击Create Actions创建。

unity的enter输入 unity输入系统_游戏引擎_03

2、在想要控制的物体上挂载组件Player Input,如上图所示组件,之后绑定对应的Input Actions。

如果想要创建跳跃,射击之类的动作,可以双击创建创建的Input Actions或者选中此文件单击Edit asset

unity的enter输入 unity输入系统_c#_04


进入配置界面

unity的enter输入 unity输入系统_游戏引擎_05


点击加号分别创建Action Map,Action并绑定按键

unity的enter输入 unity输入系统_unity的enter输入_06


unity的enter输入 unity输入系统_unity的enter输入_07


如上图所示,Behavior有很多种模式,这里使用的Send Messages,使用此模式会调用下方所示信息中的方法。

跳跃

Will SendMessage() to GameOject: OnDeviceLost, OnDeviceRegained,OncontrolsChanged, OnJump

所以我们要想在按钮被点击时触发应有的事件,就需要创建对应的方法名的方法,创建了一个Player脚本文件并挂载到该物体上,创建如下脚本文件:

using UnityEngine.InputSystem;//需要引用的命名空间
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    public  void OnJump() 
    {
        transform.Translate(Vector3.up);
        Debug.Log("跳跃");
    }
    
}

运行后成功执行:

unity的enter输入 unity输入系统_unity_08

移动

更改Input Actions,添加一个Action,

Action Type为Value,Control Type为Vector 2

删除下方绑定

unity的enter输入 unity输入系统_unity_09


右键该Action

unity的enter输入 unity输入系统_重启_10


创建一个上下左右的组合

unity的enter输入 unity输入系统_unity_11


绑定对应的按键

创建如下脚本:

using UnityEngine.InputSystem;
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    void OnMove(InputValue value)
    {
        Debug.Log(value.Get<Vector2>());
    }
}

通过测试我们可以发现输出为:

unity的enter输入 unity输入系统_游戏引擎_12


所以移动代码可以为:

using UnityEngine.InputSystem;
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    public float MoveSpeed;
    void OnMove(InputValue value)
    {
        transform.Translate(value.Get<Vector2>()*MoveSpeed*Time.deltaTime);
    }
}

但是这种情况下并不能实现连续移动,因为事件只能在按键按下时响应一次。
但是根据根据其数值输出按下为1抬起为0,我们或许可以这样做来完成连续移动:

using UnityEngine.InputSystem;
using UnityEngine;

public class PlayerController : MonoBehaviour
{
    public float MoveSpeed;
    public Vector2 move;
    void OnMove(InputValue value)
    {
       move= value.Get<Vector2>() * MoveSpeed * Time.deltaTime;
    }
    private void Update()
    {
        transform.Translate(new Vector3(move.x,0,move.y));
    }
}