| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667 |
- 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<LayoutElement>();
- le.preferredHeight = this.GetComponent<LayoutElement>().preferredHeight;
- le.preferredWidth = this.GetComponent<LayoutElement>().preferredWidth;
- le.flexibleHeight = this.GetComponent<LayoutElement>().flexibleHeight;
- le.flexibleWidth = this.GetComponent<LayoutElement>().flexibleWidth;
- le.minHeight = this.GetComponent<LayoutElement>().minHeight;
- le.minWidth = this.GetComponent<LayoutElement>().minWidth;
- placeholder.transform.SetSiblingIndex(this.transform.GetSiblingIndex());
- parent = this.transform.parent;
- placeholderParent = parent;
- GetComponent<CanvasGroup>().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<CanvasGroup>().blocksRaycasts = true;
- Destroy(placeholder);
- }
- }
|