KeyRebindButton.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. using System;
  2. using UnityEngine;
  3. namespace MeidoPhotoStudio.Plugin;
  4. public class KeyRebindButton : BaseControl
  5. {
  6. private readonly Button button;
  7. private bool listening;
  8. private KeyCode keyCode;
  9. public KeyRebindButton(KeyCode code)
  10. {
  11. button = new(code.ToString());
  12. button.ControlEvent += (_, _) =>
  13. StartListening();
  14. }
  15. public KeyCode KeyCode
  16. {
  17. get => keyCode;
  18. set
  19. {
  20. keyCode = value;
  21. button.Label = keyCode.ToString();
  22. }
  23. }
  24. public override void Draw(params GUILayoutOption[] layoutOptions)
  25. {
  26. var buttonStyle = new GUIStyle(GUI.skin.button);
  27. Draw(buttonStyle, layoutOptions);
  28. }
  29. public void Draw(GUIStyle buttonStyle, params GUILayoutOption[] layoutOptions)
  30. {
  31. GUI.enabled = !listening && !InputManager.Listening;
  32. button.Draw(buttonStyle, layoutOptions);
  33. GUI.enabled = true;
  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. KeyCode = InputManager.CurrentKeyCode is not KeyCode.Escape ? InputManager.CurrentKeyCode : KeyCode;
  46. InputManager.KeyChange -= KeyChange;
  47. OnControlEvent(EventArgs.Empty);
  48. }
  49. }