【Unity程序技巧】Input管理器


👨‍💻个人主页@元宇宙-秩沅

👨‍💻 hallo 欢迎 点赞👍 收藏⭐ 留言📝 加关注✅!

👨‍💻 本文由 秩沅 原创

👨‍💻 收录于专栏Unity基础实战

⭐🅰️⭐



文章目录


⭐前言⭐


🎶(W)PC_Input管理器


1.相关知识

2.特点

  • 配合事件中心管理器和公共Update管理器使用
  • 主要用于检测输入事件然后与事件中心配套使用
  • 使用场景: 更换玩家时进行相同的操作
3.脚本
csharp 复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;


public class InputManager : SingleManager<InputManager>
{
    private bool isStart = false;


    public InputManager()
    {
        UpdateManager.GetInstance().AddUpdateListener(MyUpdate);
    }


    // 是否开启输入检测

    public void OpenOrClose(bool flag)
    {
        isStart = flag;
    }

    private void MyUpdate() //执行时已变成生命函数Update
    {
        if (!isStart) return;
        CheckKeyCode(KeyCode.W);
        CheckKeyCode(KeyCode.S);
        CheckKeyCode(KeyCode.A);
        CheckKeyCode(KeyCode.D);
    }

 
    // 分发输入事件给事件中心

    private void CheckKeyCode(object  key)
    {
        KeyCode code = (KeyCode)key;

  
        if (Input.GetKeyDown(code))
            EventCenter.GetInstance().EventTrigger("按下某键", key);

        //由于传进来的参数是枚举类型,而事件中心的构建不支持所以,传进事件中心的还是Object类型

    }

	//可自定义构造其他传入事件中心的组合
}
  • 测试
csharp 复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

public class text : MonoBehaviour
{

    void Start()
    {
        //开启输入检测
        InputManager.GetInstance().OpenOrClose(true);

        //添加事件到事件中心
        EventCenter.GetInstance().AddEventListener<object>("按下某键", KeyDown);

    }
             
    public void KeyDown( object key)
    {
        KeyCode code =(KeyCode)key ;
        switch (code)
        {
            case KeyCode.W:
                Debug.Log("前进");
                break;
            case KeyCode.S:
                Debug.Log("后退");
                break;
            case KeyCode.A:
                Debug.Log("向左");
                break;
            case KeyCode.D:
                Debug.Log("向右");
                break;
        }

    }


}

    

⭐🅰️⭐


【Unityc#专题篇】之c#进阶篇】

【Unityc#专题篇】之c#核心篇】

【Unityc#专题篇】之c#基础篇】

【Unity-c#专题篇】之c#入门篇】

【Unityc#专题篇】---进阶章题单实践练习

【Unityc#专题篇】---基础章题单实践练习

【Unityc#专题篇】---核心章题单实践练习


你们的点赞👍 收藏⭐ 留言📝 关注✅是我持续创作,输出优质内容的最大动力!



相关推荐
XR-AI-JK2 小时前
Unity VR/MR开发-VR/开发SDK选型对比分析
unity·vr·mr
心之所向,自强不息10 小时前
【Unity Shader编程】之让画面动起来
unity·游戏引擎
不伤欣1 天前
游戏设计模式 - 子类沙箱
游戏·unity·设计模式
Magnum Lehar1 天前
vulkan游戏引擎test文件memory实现
游戏引擎
Magnum Lehar1 天前
vulkan游戏引擎test_manager实现
java·算法·游戏引擎
快乐觉主吖2 天前
Unity的日志管理类
android·unity·游戏引擎
WarPigs2 天前
Unity性能优化笔记
笔记·unity·游戏引擎
T.D.C2 天前
【业务框架】3C-相机-Cinemachine
unity
一线灵2 天前
跨平台游戏引擎 Axmol-2.6.1 发布
游戏引擎
Clank的游戏栈3 天前
Unity基于GraphView的可视化关卡编辑器开发指南
unity·编辑器·游戏引擎