目录
一.新输入系统相较于旧版输入系统的优势
1.便于处理不同输入设备的输入信号,多平台开发
2.动作基于事件,更具有灵活性和扩展性
3.输入调试系统,可以准确的看到输入值
4.引入了动作表,当玩家不同状态时同一按键实现不同功能
二.新输入系统的安装
双击打开,并添加按键
三.基于PlayerInput的使用
在组件上搜索添加内置的PlayerInput组件,并将创建好的InputActions拖入其中即可,然后为按键添加事件
四.基于C#脚本使用InputSystem(推荐)
首先我们让创建好的InputActions生成同名的C#脚本
新建一个脚本和生成的InputActions脚本进行结合使用
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.InputSystem;
//这里有两个动作表,我们分别继承他们的接口并实现函数
public class MyInputSystem : MonoBehaviour, InputActions.IGamePlayerActions, InputActions.IUIActions
{
InputActions inputActions;
private void Awake()
{
inputActions = new InputActions();
}
private void OnEnable()
{
//--注册动作表
inputActions.GamePlayer.SetCallbacks(this);
inputActions.UI.SetCallbacks(this);
//--启用动作表(游戏运行状态的动作表)
inputActions.GamePlayer.Enable();
}
//----实现功能
//开始时玩家处于游戏运行状态按下WASD移动物体,F进入菜单模式
//在菜单模式下同样按F实现不同效果,按ESC返回游戏运行状态
public void OnMove(InputAction.CallbackContext context)
{
if (context.phase == InputActionPhase.Performed)
{
//因为创建的是Vector2类型按键,该按键带有参数
Debug.Log(context.ReadValue<Vector2>());
}
if (context.phase == InputActionPhase.Canceled)
{
Debug.Log("停止");
}
}
public void OnFire(InputAction.CallbackContext context)
{
if (context.phase == InputActionPhase.Started)
{
//游戏运行状态下按下F进入菜单模式
Debug.Log("进入菜单模式");
//切换动作表
inputActions.GamePlayer.Disable();//禁用游戏运行状态动作表
inputActions.UI.Enable();//启用菜单动作表
}
}
public void OnESC(InputAction.CallbackContext context)
{
if (context.phase == InputActionPhase.Started)
{
Debug.Log("进入游戏运行模式");
//切换动作表
inputActions.UI.Disable();//禁用菜单动作表
inputActions.GamePlayer.Enable();//启用游戏运行状态动作表
}
}
public void OnF(InputAction.CallbackContext context)
{
if (context.phase == InputActionPhase.Performed)
{
Debug.Log("菜单状体下:FFF!!!");
}
}
}
最后经过测试,达到了预期效果
以上就是我对InputSystem的使用总结