:::info 结合输入控制模块实现改建功能非常方便 :::

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class InputMgr : BaseManager<InputMgr>
  5. {
  6. private bool isOpen = false;
  7. public InputMgr()
  8. {
  9. MonoMgr.GetInstance().AddUpdateListener(MyUpdate);
  10. }
  11. private void MyUpdate()
  12. {
  13. // 如果没开启检测则不检测
  14. if (!isOpen)
  15. return;
  16. CheckKeyCode(KeyCode.W);
  17. CheckKeyCode(KeyCode.S);
  18. CheckKeyCode(KeyCode.A);
  19. CheckKeyCode(KeyCode.D);
  20. }
  21. /// <summary>
  22. /// 用来检测按键按下抬起,分发事件
  23. /// </summary>
  24. /// <param name="key"></param>
  25. private void CheckKeyCode(KeyCode key)
  26. {
  27. if(Input.GetKeyDown(key))
  28. {
  29. EventCenter.GetInstance().EventTrigger("某键按下", key);
  30. }
  31. if(Input.GetKeyUp(key))
  32. {
  33. EventCenter.GetInstance().EventTrigger("某键抬起", key);
  34. }
  35. }
  36. // 控制输入检测的开关
  37. public void StartOrEndCheck(bool isOpen)
  38. {
  39. this.isOpen = isOpen;
  40. }
  41. }

例子

  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. public class InputTest : MonoBehaviour
  5. {
  6. // Start is called before the first frame update
  7. void Start()
  8. {
  9. // 开启输入检测
  10. InputMgr.GetInstance().StartOrEndCheck(true);
  11. // 添加事件监听 [玩家死亡的时候只需要移除监听,就不会再检测]
  12. EventCenter.GetInstance().AddEventListener("某键按下", CheckInputDown);
  13. EventCenter.GetInstance().AddEventListener("某键抬起", CheckInputUp);
  14. }
  15. private void CheckInputDown(object key)
  16. {
  17. KeyCode keyCode = (KeyCode)key;
  18. switch(keyCode)
  19. {
  20. case KeyCode.W:
  21. Debug.Log("W_Down");
  22. break;
  23. case KeyCode.S:
  24. Debug.Log("S_Down");
  25. break;
  26. case KeyCode.A:
  27. Debug.Log("A_Down");
  28. break;
  29. case KeyCode.D:
  30. Debug.Log("D_Down");
  31. break;
  32. }
  33. }
  34. private void CheckInputUp(object key)
  35. {
  36. KeyCode keyCode = (KeyCode)key;
  37. switch (keyCode)
  38. {
  39. case KeyCode.W:
  40. Debug.Log("W_UP");
  41. break;
  42. case KeyCode.S:
  43. Debug.Log("S_UP");
  44. break;
  45. case KeyCode.A:
  46. Debug.Log("A_UP");
  47. break;
  48. case KeyCode.D:
  49. Debug.Log("D_UP");
  50. break;
  51. }
  52. }
  53. }

改键