KeyRebindButton.cs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. using System;
  2. using UnityEngine;
  3. namespace COM3D2.MeidoPhotoStudio.Plugin
  4. {
  5. public class KeyRebindButton : BaseControl
  6. {
  7. private readonly Button button;
  8. private bool listening;
  9. private KeyCode keyCode;
  10. public KeyCode KeyCode
  11. {
  12. get => keyCode;
  13. set
  14. {
  15. keyCode = value;
  16. button.Label = keyCode.ToString();
  17. }
  18. }
  19. public KeyRebindButton(KeyCode code)
  20. {
  21. button = new Button(code.ToString());
  22. button.ControlEvent += (s, a) => StartListening();
  23. }
  24. public void Draw(GUIStyle buttonStyle, params GUILayoutOption[] layoutOptions)
  25. {
  26. GUI.enabled = !listening && !InputManager.Listening;
  27. button.Draw(buttonStyle, layoutOptions);
  28. GUI.enabled = true;
  29. }
  30. public override void Draw(params GUILayoutOption[] layoutOptions)
  31. {
  32. GUIStyle buttonStyle = new GUIStyle(GUI.skin.button);
  33. Draw(buttonStyle, layoutOptions);
  34. }
  35. private void StartListening()
  36. {
  37. listening = true;
  38. button.Label = string.Empty;
  39. InputManager.StartListening();
  40. InputManager.KeyChange += KeyChange;
  41. }
  42. private void KeyChange(object sender, EventArgs args)
  43. {
  44. listening = false;
  45. if (InputManager.CurrentKeyCode != KeyCode.Escape) KeyCode = InputManager.CurrentKeyCode;
  46. else KeyCode = KeyCode;
  47. InputManager.KeyChange -= KeyChange;
  48. OnControlEvent(EventArgs.Empty);
  49. }
  50. }
  51. }