【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#专题篇】---核心章题单实践练习


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



相关推荐
心前阳光17 小时前
Unity发布PC软件图标不能改变
unity·游戏引擎
an86950011 天前
unity如何在visual studio中打断点debug
unity·游戏引擎·visual studio
xcLeigh1 天前
Unity基础:使用Transform控制物体移动——Translate与position详解
unity·游戏引擎
FairGuard手游加固1 天前
Unity小游戏加密:global-metadata.dat与AssetBundle保护
游戏·unity·游戏引擎
狂人开飞机1 天前
11、UI系统
游戏引擎·godot
真鬼1231 天前
【Unity AI】Untiy链接cursor与MCP
unity·游戏引擎
WarPigs1 天前
Unity设置人物位置无效的原因
unity
程序员正茂1 天前
Unity3d行为树Behavior Designer Pro
unity·行为树
郝学胜-神的一滴1 天前
C++11 工程级应用 10:减少拷贝,让容器跑得更快
服务器·开发语言·c++·游戏引擎·opengl
玖玥拾1 天前
Lua 基础语法(八) Unity Huatuo (HybridCLR)
开发语言·unity·游戏引擎·lua