using System; using Sirenix.OdinInspector; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; namespace Ether { [RequireComponent(typeof(Image))] public class ToggleEx : SerializedMonoBehaviour, IPointerClickHandler, IPointerDownHandler, IPointerUpHandler { [LabelText("选择状态显示")] [PropertyOrder(1)] public GameObject checkRoot; [LabelText("非选择状态显示")][PropertyOrder(2)] public GameObject uncheckRoot; [PropertySpace(20)] [LabelText("选择状态")] [ShowInInspector] [PropertyOrder(3)] public bool IsOn { set { isOn = value; SetIsOnState(); } get => isOn; } private bool isOn; [PropertySpace(20)] [LabelText("组")] [PropertyOrder(4)] public ToggleGroupEx toggleGroup; /// /// 值改变事件 /// public ActionEvent OnValueChange { get; } = new ActionEvent(); private void Awake() { if (toggleGroup) { toggleGroup.AddToggle(this); } } public void OnPointerClick(PointerEventData eventData) { if (toggleGroup != null && IsOn) { return; } isOn = !isOn; SetIsOnState(); OnValueChange.Invoke(IsOn); } private void SetIsOnState() { checkRoot?.SetActive(isOn); uncheckRoot?.SetActive(!isOn); if (isOn && toggleGroup != null) { toggleGroup.SetToggleSelected(this); } } // 在编辑器模式下,当脚本中的公共变量发生变化时调用此方法 private void OnValidate() { // 如果在编辑器模式下,提示用户检查这些字段是否已分配 #if UNITY_EDITOR if (uncheckRoot == null) { Transform trans = transform.Find("Uncheck"); if (trans != null) { uncheckRoot = trans.gameObject; } else { uncheckRoot = new GameObject("Uncheck", typeof(RectTransform)); uncheckRoot.transform.SetParent(transform); } uncheckRoot.transform.localPosition = Vector3.zero; RectTransform rect = uncheckRoot.GetComponent(); rect.anchorMin = Vector2.zero; rect.anchorMax = new Vector2(1, 1); rect.sizeDelta = Vector2.zero; } if (checkRoot == null) { Transform trans = transform.Find("Check"); if (trans != null) { checkRoot = trans.gameObject; } else { checkRoot = new GameObject("Check", typeof(RectTransform)); checkRoot.transform.SetParent(transform); } checkRoot.transform.localPosition = Vector3.zero; RectTransform rect = checkRoot.GetComponent(); rect.anchorMin = Vector2.zero; rect.anchorMax = new Vector2(1, 1); rect.sizeDelta = Vector2.zero; } Image img = GetComponent(); if (img.color.a != 0) { img.color = new Color(1, 1, 1, 0); } #endif } public void OnPointerDown(PointerEventData eventData) { } public void OnPointerUp(PointerEventData eventData) { } } }