unity---输入模块

InputMgr#

利用到事件中心

测试代码#

image
image

添加Update监听#

image

开关#

image

代码汇总#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class InputMgr : Singleton<InputMgr>
{
    private bool isStart=false;
    public InputMgr(){
        MonoMgr.Instance.AddUpdateListener(MyUpdate);
    }
    public void StartOrEndCheck(bool isOpen){
        isStart = isOpen;
    }
    private void CheckKeyCode(KeyCode key){
        if(Input.GetKeyDown(key)){
            EventCenter.Instance.EventTrigger("某键按下",key);
        }
        if(Input.GetKeyUp(key)){
            EventCenter.Instance.EventTrigger("某键抬起",key);
        }

    }
    private void MyUpdate(){
        if(!isStart){return ;}
		     // 循环检测,这四种键是否被按下,如果被按下就触发事件
        CheckKeyCode(KeyCode.W);
          CheckKeyCode(KeyCode.S);
            CheckKeyCode(KeyCode.D);
              CheckKeyCode(KeyCode.A);
    }

}

测试代码#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;

public class InputTest : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        Debug.Log("开始了");
        //开启输入检测
        InputMgr.Instance.StartOrEndCheck(true);
        //添加事件监听
        EventCenter.Instance.AddEventListener("某键按下",CheckInputDown);
        EventCenter.Instance.AddEventListener("某键抬起",CheckInputUp);
    }
    private void CheckInputDown(object key){
        Debug.Log("按下");
        KeyCode code = (KeyCode)key;
        switch(code){
            case KeyCode.W:Debug.Log("前进");
                break;
            case KeyCode.A:
                Debug.Log("左转");
                break;
            case KeyCode.S:
                Debug.Log("后退");
                break;
            case KeyCode.D:
                Debug.Log("右转");
                break;          
        }
        
    }
    private void CheckInputUp(object key){
        Debug.Log("抬起");
        KeyCode code = (KeyCode)key;
        switch(code){
             case KeyCode.W:Debug.Log("停止前进");
                break;
            case KeyCode.A:
                Debug.Log("停止左转");
                break;
            case KeyCode.S:
                Debug.Log("停止后退");
                break;
            case KeyCode.D:
                Debug.Log("停止右转");
                break;      
        }
    }
    // Update is called once per frame
}


posted @   lxp_blog  阅读(56)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
点击右上角即可分享
微信分享提示
主题色彩