:::info 结合输入控制模块实现改建功能非常方便 :::
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class InputMgr : BaseManager<InputMgr>
{
private bool isOpen = false;
public InputMgr()
{
MonoMgr.GetInstance().AddUpdateListener(MyUpdate);
}
private void MyUpdate()
{
// 如果没开启检测则不检测
if (!isOpen)
return;
CheckKeyCode(KeyCode.W);
CheckKeyCode(KeyCode.S);
CheckKeyCode(KeyCode.A);
CheckKeyCode(KeyCode.D);
}
/// <summary>
/// 用来检测按键按下抬起,分发事件
/// </summary>
/// <param name="key"></param>
private void CheckKeyCode(KeyCode key)
{
if(Input.GetKeyDown(key))
{
EventCenter.GetInstance().EventTrigger("某键按下", key);
}
if(Input.GetKeyUp(key))
{
EventCenter.GetInstance().EventTrigger("某键抬起", key);
}
}
// 控制输入检测的开关
public void StartOrEndCheck(bool isOpen)
{
this.isOpen = isOpen;
}
}
例子
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class InputTest : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
// 开启输入检测
InputMgr.GetInstance().StartOrEndCheck(true);
// 添加事件监听 [玩家死亡的时候只需要移除监听,就不会再检测]
EventCenter.GetInstance().AddEventListener("某键按下", CheckInputDown);
EventCenter.GetInstance().AddEventListener("某键抬起", CheckInputUp);
}
private void CheckInputDown(object key)
{
KeyCode keyCode = (KeyCode)key;
switch(keyCode)
{
case KeyCode.W:
Debug.Log("W_Down");
break;
case KeyCode.S:
Debug.Log("S_Down");
break;
case KeyCode.A:
Debug.Log("A_Down");
break;
case KeyCode.D:
Debug.Log("D_Down");
break;
}
}
private void CheckInputUp(object key)
{
KeyCode keyCode = (KeyCode)key;
switch (keyCode)
{
case KeyCode.W:
Debug.Log("W_UP");
break;
case KeyCode.S:
Debug.Log("S_UP");
break;
case KeyCode.A:
Debug.Log("A_UP");
break;
case KeyCode.D:
Debug.Log("D_UP");
break;
}
}
}