unity---输入模块
InputMgr#
利用到事件中心
测试代码#
添加Update监听#
开关#
代码汇总#
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
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!