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
}

浙公网安备 33010602011771号