IndieGame/client/Assets/Ether/Scripts/Module/Extension/UGUI/Toggle/ToggleEx.cs
2024-10-31 10:58:14 +08:00

161 lines
4.4 KiB
C#

using System;
using Sirenix.OdinInspector;
using System.Collections;
using System.Collections.Generic;
#if UNITY_EDITOR
using UnityEditor;
#endif
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;
/// <summary>
/// 值改变事件
/// </summary>
public ActionEvent<bool> OnValueChange { get; } = new ActionEvent<bool>();
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)
{
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<RectTransform>();
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<RectTransform>();
rect.anchorMin = Vector2.zero;
rect.anchorMax = new Vector2(1, 1);
rect.sizeDelta = Vector2.zero;
}
Image img = GetComponent<Image>();
if (img.color.a != 0)
{
img.color = new Color(1, 1, 1, 0);
}
#endif
}
public void OnPointerDown(PointerEventData eventData)
{
}
public void OnPointerUp(PointerEventData eventData)
{
}
#if UNITY_EDITOR
[MenuItem("GameObject/UIEx/ToggleEx", priority = -997)]
private static void CreateToggleEx(MenuCommand menuCmd)
{
GameObject selection = Selection.activeGameObject;
CommonExtension.CreateComponent<ToggleEx>(selection, (obj) =>
{
obj.GetComponent<Image>().color = new Color(1, 1, 1, 0);
}, typeof(Image));
}
#endif
}
}