| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253 |
- using System;
- using UnityEngine;
- using UnityEngine.UI;
- using UnityEngine.EventSystems;
- namespace JCUnityLib.UI
- {
- [ExecuteAlways]
- [RequireComponent(typeof(RectBorder))]
- public class TwoPoleSwitch : MonoBehaviour, IPointerClickHandler
- {
- public RectTransform rectTransform { get => transform as RectTransform; }
- public RectTransform point;
- [SerializeField] bool _isSwitchOn = true;
- public bool isSwitchOn
- {
- get => _isSwitchOn;
- set
- {
- _isSwitchOn = value;
- UpdateStatus();
- }
- }
- public Color colorSwitchOn = new Color(99/255f, 221/255f, 251/255f, 1);
- public Color colorSwitchOff = new Color(142/255f, 142/255f, 142/255f, 1);
- public Func<bool, bool> onClick;
- Image _image;
- void Start()
- {
- UpdateStatus();
- }
- void Update()
- {
- #if UNITY_EDITOR
- UpdateStatus();
- #endif
- }
- void UpdateStatus()
- {
- if (!_image) _image = GetComponent<Image>();
- _image.color = isSwitchOn ? colorSwitchOn : colorSwitchOff;
- var borderWidth = (rectTransform.rect.height - point.rect.height) / 2;
- point.localPosition = (isSwitchOn ? Vector2.right : Vector2.left) * (rectTransform.rect.width / 2 - borderWidth - point.rect.width / 2);
- }
- public void OnPointerClick(PointerEventData eventData)
- {
- bool nextStatus = !isSwitchOn;
- bool canChange = true;
- if (onClick != null) canChange = onClick.Invoke(nextStatus);
- if (canChange) isSwitchOn = nextStatus;
- }
- }
- }
|