TwoPoleSwitch.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. using System;
  2. using UnityEngine;
  3. using UnityEngine.UI;
  4. using UnityEngine.EventSystems;
  5. namespace JCUnityLib.UI
  6. {
  7. [ExecuteAlways]
  8. [RequireComponent(typeof(RectBorder))]
  9. public class TwoPoleSwitch : MonoBehaviour, IPointerClickHandler
  10. {
  11. public RectTransform rectTransform { get => transform as RectTransform; }
  12. public RectTransform point;
  13. [SerializeField] bool _isSwitchOn = true;
  14. public bool isSwitchOn
  15. {
  16. get => _isSwitchOn;
  17. set
  18. {
  19. _isSwitchOn = value;
  20. UpdateStatus();
  21. }
  22. }
  23. public Color colorSwitchOn = new Color(99/255f, 221/255f, 251/255f, 1);
  24. public Color colorSwitchOff = new Color(142/255f, 142/255f, 142/255f, 1);
  25. public Func<bool, bool> onClick;
  26. Image _image;
  27. void Start()
  28. {
  29. UpdateStatus();
  30. }
  31. void Update()
  32. {
  33. #if UNITY_EDITOR
  34. UpdateStatus();
  35. #endif
  36. }
  37. void UpdateStatus()
  38. {
  39. if (!_image) _image = GetComponent<Image>();
  40. _image.color = isSwitchOn ? colorSwitchOn : colorSwitchOff;
  41. var borderWidth = (rectTransform.rect.height - point.rect.height) / 2;
  42. point.localPosition = (isSwitchOn ? Vector2.right : Vector2.left) * (rectTransform.rect.width / 2 - borderWidth - point.rect.width / 2);
  43. }
  44. public void OnPointerClick(PointerEventData eventData)
  45. {
  46. bool nextStatus = !isSwitchOn;
  47. bool canChange = true;
  48. if (onClick != null) canChange = onClick.Invoke(nextStatus);
  49. if (canChange) isSwitchOn = nextStatus;
  50. }
  51. }
  52. }