using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.UI; public class Draggable : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler { public Vector3 startPosition; public Transform parent = null; public Transform placeholderParent = null; GameObject placeholder = null; public void OnDrag(PointerEventData eventData) { this.transform.position = eventData.position; if (placeholder.transform.parent != placeholderParent) { placeholder.transform.SetParent(placeholderParent); } int newSiblingIndex = placeholderParent.childCount; for (int i = 0; i < placeholderParent.childCount; i++) { if (this.transform.position.x < placeholderParent.GetChild(i).transform.position.x) { newSiblingIndex = i; if (parent.transform.GetSiblingIndex() < newSiblingIndex) { newSiblingIndex--; } break; } } placeholderParent.transform.SetSiblingIndex(newSiblingIndex); } public void OnBeginDrag(PointerEventData eventData) { startPosition = this.transform.position; placeholder = new GameObject(); placeholder.transform.SetParent(this.transform.parent); LayoutElement le = placeholder.AddComponent(); le.preferredHeight = this.GetComponent().preferredHeight; le.preferredWidth = this.GetComponent().preferredWidth; le.flexibleHeight = this.GetComponent().flexibleHeight; le.flexibleWidth = this.GetComponent().flexibleWidth; le.minHeight = this.GetComponent().minHeight; le.minWidth = this.GetComponent().minWidth; placeholder.transform.SetSiblingIndex(this.transform.GetSiblingIndex()); parent = this.transform.parent; placeholderParent = parent; GetComponent().blocksRaycasts = false; } public void OnEndDrag(PointerEventData eventData) { if (parent == null) { this.transform.position = startPosition; this.transform.SetSiblingIndex(placeholder.transform.GetSiblingIndex()); } else { this.transform.SetParent(parent); } GetComponent().blocksRaycasts = true; Destroy(placeholder); } }