Framwork/Assets/Scripts/Base/MonoBehaviour/Drag/UIDragGroup.cs

87 lines
2.1 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

using UnityEngine;
using System.Collections.Generic;
/// <summary>
/// UI拖动组管理器用于限制同时只能拖动一个UI元素
/// </summary>
public class UIDragGroup : MonoBehaviour
{
private static UIDragGroup instance;
private HashSet<UIDragHandler> dragHandlers = new HashSet<UIDragHandler>();
private UIDragHandler activeDragHandler = null;
private void Awake()
{
if (instance == null)
{
instance = this;
DontDestroyOnLoad(gameObject);
}
else
{
Destroy(gameObject);
}
}
/// <summary>
/// 注册拖动处理器
/// </summary>
public static void RegisterDragHandler(UIDragHandler handler)
{
if (instance != null)
{
instance.dragHandlers.Add(handler);
}
}
/// <summary>
/// 取消注册拖动处理器
/// </summary>
public static void UnregisterDragHandler(UIDragHandler handler)
{
if (instance != null)
{
instance.dragHandlers.Remove(handler);
if (instance.activeDragHandler == handler)
{
instance.activeDragHandler = null;
}
}
}
/// <summary>
/// 开始拖动处理
/// </summary>
public static bool BeginDrag(UIDragHandler handler)
{
if (instance == null) return true;
// 如果已有活动的拖动处理器且不是当前处理器,则拒绝拖动
if (instance.activeDragHandler != null && instance.activeDragHandler != handler)
{
return false;
}
instance.activeDragHandler = handler;
return true;
}
/// <summary>
/// 结束拖动处理
/// </summary>
public static void EndDrag(UIDragHandler handler)
{
if (instance != null && instance.activeDragHandler == handler)
{
instance.activeDragHandler = null;
}
}
private void OnDestroy()
{
if (instance == this)
{
instance = null;
}
}
}