KeyboardButtonStates.cs 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. #if UNITY_EDITOR
  2. using UnityEngine;
  3. using System.Collections.Generic;
  4. namespace O3DWB
  5. {
  6. public class KeyboardButtonStates : Singleton<KeyboardButtonStates>
  7. {
  8. #region Private Variables
  9. private Dictionary<KeyCode, bool> _keyboardButtonStates = new Dictionary<KeyCode, bool>();
  10. #endregion
  11. #region Public Methods
  12. public void ClearStates()
  13. {
  14. _keyboardButtonStates.Clear();
  15. }
  16. public void OnKeyboardButtonPressed(KeyCode keyCode)
  17. {
  18. AddKeyCodeEntryIfNecessary(keyCode);
  19. _keyboardButtonStates[keyCode] = true;
  20. }
  21. public void OnKeyboardButtonReleased(KeyCode keyCode)
  22. {
  23. AddKeyCodeEntryIfNecessary(keyCode);
  24. _keyboardButtonStates[keyCode] = false;
  25. }
  26. public bool IsKeyboardButtonPressed(KeyCode keyCode)
  27. {
  28. if (keyCode == KeyCode.LeftShift || keyCode == KeyCode.RightShift) return Event.current.shift;
  29. if (keyCode == KeyCode.LeftControl || keyCode == KeyCode.RightControl) return Event.current.control;
  30. if (keyCode == KeyCode.LeftCommand || keyCode == KeyCode.RightCommand) return Event.current.command;
  31. if (!DoesKeyCodeEntryExist(keyCode)) return false;
  32. return _keyboardButtonStates[keyCode];
  33. }
  34. public void RepairCTRLAndCMDStates()
  35. {
  36. if(!Event.current.control)
  37. {
  38. if (IsKeyboardButtonPressed(KeyCode.LeftControl)) SetKeyPressed(KeyCode.LeftControl, false);
  39. if (IsKeyboardButtonPressed(KeyCode.RightControl)) SetKeyPressed(KeyCode.RightControl, false);
  40. }
  41. if(!Event.current.command)
  42. {
  43. if (IsKeyboardButtonPressed(KeyCode.LeftCommand)) SetKeyPressed(KeyCode.LeftCommand, false);
  44. if (IsKeyboardButtonPressed(KeyCode.RightCommand)) SetKeyPressed(KeyCode.RightCommand, false);
  45. }
  46. }
  47. public bool IsAnyShiftKeyPressed()
  48. {
  49. return Event.current.shift;
  50. }
  51. public bool IsAnyCtrlKeyPressed()
  52. {
  53. return Event.current.control;
  54. }
  55. public bool IsAnyAltKeyPressed()
  56. {
  57. return Event.current.alt;
  58. }
  59. #endregion
  60. #region Private Methods
  61. private void AddKeyCodeEntryIfNecessary(KeyCode keyCode)
  62. {
  63. if (!DoesKeyCodeEntryExist(keyCode)) _keyboardButtonStates.Add(keyCode, false);
  64. }
  65. private bool DoesKeyCodeEntryExist(KeyCode keyCode)
  66. {
  67. return _keyboardButtonStates.ContainsKey(keyCode);
  68. }
  69. private void SetKeyPressed(KeyCode keyCode, bool pressed)
  70. {
  71. AddKeyCodeEntryIfNecessary(keyCode);
  72. _keyboardButtonStates[keyCode] = pressed;
  73. }
  74. #endregion
  75. }
  76. }
  77. #endif