2025-05-18 01:04:31 +08:00

89 lines
2.7 KiB
C#

// ***********************************************************************
// Assembly : Unity
// Author : KimCh
// Created :
//
// Last Modified By : KimCh
// Last Modified On :
// ***********************************************************************
// <copyright file= "KDraggable" company=""></copyright>
// <summary></summary>
// ***********************************************************************
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
public class KDraggable : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler
{
public UnityEngine.Events.UnityEvent onDragEnd = new UnityEngine.Events.UnityEvent();
[HideInInspector]
public Transform parentToReturnTo = null;
[HideInInspector]
public Transform placeHolderParent = null;
private GameObject _placeHolder = null;
private LayoutElement _layoutElement;
private void Awake()
{
_layoutElement = GetComponent<LayoutElement>();
}
public void OnBeginDrag(PointerEventData eventData)
{
_placeHolder = new GameObject();
_placeHolder.transform.SetParent(this.transform.parent);
var le = _placeHolder.AddComponent<LayoutElement>();
le.preferredWidth = _layoutElement.preferredWidth;
le.preferredHeight = _layoutElement.preferredHeight;
_placeHolder.transform.SetSiblingIndex(this.transform.GetSiblingIndex());
parentToReturnTo = this.transform.parent;
placeHolderParent = parentToReturnTo;
_layoutElement.ignoreLayout = true;
this.transform.SetParent(this.transform.parent.parent);
this.GetComponent<CanvasGroup>().blocksRaycasts = false;
}
public void OnDrag(PointerEventData eventData)
{
if (_placeHolder.transform.parent != placeHolderParent)
{
_placeHolder.transform.SetParent(placeHolderParent);
}
RectTransformUtility.ScreenPointToWorldPointInRectangle(this.transform as RectTransform, eventData.position, eventData.pressEventCamera, out var position);
this.transform.position = position;
int newSiblingIndex = placeHolderParent.childCount;
for (int i = 0; i < placeHolderParent.childCount; i++)
{
var child = placeHolderParent.GetChild(i);
if (child.gameObject.activeSelf && position.x < child.position.x)
{
newSiblingIndex = i;
if (_placeHolder.transform.GetSiblingIndex() < newSiblingIndex)
newSiblingIndex--;
break;
}
}
_placeHolder.transform.SetSiblingIndex(newSiblingIndex);
}
public void OnEndDrag(PointerEventData eventData)
{
_layoutElement.ignoreLayout = false;
this.transform.SetParent(parentToReturnTo);
this.GetComponent<CanvasGroup>().blocksRaycasts = true;
this.transform.SetSiblingIndex(_placeHolder.transform.GetSiblingIndex());
Destroy(_placeHolder);
onDragEnd.Invoke();
}
}