KeyRebindButton.cs 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  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 KeyCode KeyCode
  10. {
  11. get => keyCode;
  12. set
  13. {
  14. keyCode = value;
  15. button.Label = keyCode.ToString();
  16. }
  17. }
  18. public KeyRebindButton(KeyCode code)
  19. {
  20. button = new(code.ToString());
  21. button.ControlEvent += (_, _) =>
  22. 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. var 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. KeyCode = InputManager.CurrentKeyCode is not KeyCode.Escape ? InputManager.CurrentKeyCode : KeyCode;
  46. InputManager.KeyChange -= KeyChange;
  47. OnControlEvent(EventArgs.Empty);
  48. }
  49. }