• Unity Input System最简单使用


    开始学的是 Input Manager 比较好理解,Input System却不好理解,教程也找了很多,感觉都讲的不清楚,我这里做一个最简单的用 Input System 添加鼠标左键和右键的效果。

    1. 安装 Input System 包

    首先这个功能不是内置的,需要自行安装。打开Unity上方工具栏中的 WindowPackage Manager打开Unity插件包管理界面, Package Manager是Unity的包管理工具,可以安装、卸载、升级相关的包。左上角选择 Unity Registry,在输入框搜索到结果之后,点击右下角的安装即可,安装好之后,会有一个绿色的钩。
    在这里插入图片描述

    2. 启用 Input System

    系统默认使用 Input Manager(Old) ,在 Edit → Project settings → Player中
    在这里插入图片描述
    之后unity会重启。

    3. 新建配置文件

    在一个场景中,Asset目录新建 Setting目录,放置项目的配置文件。然后右键
    Create → Input Actions。我改名叫 InputActions。
    在这里插入图片描述

    在这里插入图片描述

    4. 配置事件集合

    选中刚刚新建的 InputActions,如上图,点击Edit Asset
    在这里插入图片描述
    点击左上角,选择Add Control Schema,然后新建一个Actions Map(可以理解为一大组事件的集合,方便可以灵活切换),然后新建 Actions,比如我新建的LeftClickRightClick表示鼠标左右键点击。
    在这里插入图片描述
    点击后边的加号,选择 Add binding,添加事件绑定。
    在这里插入图片描述
    在Path里选择Mouse(鼠标)-> Left Button

    5. 生成C#文件

    在这里插入图片描述
    勾选,然后点击Apply即可。

    6. 添加游戏物体

    添加一个游戏物体,然后添加组件 PlayerInput,Actions选择我们新建的那个InputActions。
    在这里插入图片描述

    7. 脚本测试

    创建一个脚本,并且绑定到游戏对象上,比如我的 InputDemo.cs ,使用我们刚刚第5步自动生成的那个cs文件,运行游戏,点击鼠标即可。

    using UnityEngine;
    using UnityEngine.InputSystem;
    
    public class InputDemo : MonoBehaviour {
      private InputActions playerInputActions;
    
      void Awake() {
        playerInputActions = new InputActions();
      }
    
      private void OnEnable() {
        playerInputActions.UI.Enable();
      }
    
      private void OnDisable() {
        playerInputActions.UI.Disable();
      }
    
      private void OnMouseDown() {
        print("down");
      }
    
      private void Update() {
        // IsPressed会有多次
        if (playerInputActions.UI.LeftClick.IsPressed()) {
          print("点击left键");
        }
    
        // trigger只执行一次
        if (playerInputActions.UI.RightClick.triggered) {
          print("点击right键");
        }
      }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
  • 相关阅读:
    YoloV5改进策略:复现HIC-YOLOv5,用于小物体检测
    函数形状有几种定义方式;操作符infer的作用
    算法 滑动窗口
    ES6 --》字符串与数值新增方法
    VMware中虚拟机没网
    CN考研真题知识点二轮归纳(5)
    Hive环境搭建
    「学习笔记」FHQ-treap
    在Flask中处理后台任务
    Jmix 中 REST API 的两种实现
  • 原文地址:https://blog.csdn.net/qq_29334605/article/details/134288402