Draggable.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. using UnityEngine.EventSystems;
  5. using UnityEngine.UI;
  6. public class Draggable : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler {
  7. public Vector3 startPosition;
  8. public Transform parent = null;
  9. public Transform placeholderParent = null;
  10. GameObject placeholder = null;
  11. public void OnDrag(PointerEventData eventData) {
  12. this.transform.position = eventData.position;
  13. if (placeholder.transform.parent != placeholderParent) {
  14. placeholder.transform.SetParent(placeholderParent);
  15. }
  16. int newSiblingIndex = placeholderParent.childCount;
  17. for (int i = 0; i < placeholderParent.childCount; i++) {
  18. if (this.transform.position.x < placeholderParent.GetChild(i).transform.position.x) {
  19. newSiblingIndex = i;
  20. if (parent.transform.GetSiblingIndex() < newSiblingIndex) {
  21. newSiblingIndex--;
  22. }
  23. break;
  24. }
  25. }
  26. placeholderParent.transform.SetSiblingIndex(newSiblingIndex);
  27. }
  28. public void OnBeginDrag(PointerEventData eventData) {
  29. startPosition = this.transform.position;
  30. placeholder = new GameObject();
  31. placeholder.transform.SetParent(this.transform.parent);
  32. LayoutElement le = placeholder.AddComponent<LayoutElement>();
  33. le.preferredHeight = this.GetComponent<LayoutElement>().preferredHeight;
  34. le.preferredWidth = this.GetComponent<LayoutElement>().preferredWidth;
  35. le.flexibleHeight = this.GetComponent<LayoutElement>().flexibleHeight;
  36. le.flexibleWidth = this.GetComponent<LayoutElement>().flexibleWidth;
  37. le.minHeight = this.GetComponent<LayoutElement>().minHeight;
  38. le.minWidth = this.GetComponent<LayoutElement>().minWidth;
  39. placeholder.transform.SetSiblingIndex(this.transform.GetSiblingIndex());
  40. parent = this.transform.parent;
  41. placeholderParent = parent;
  42. GetComponent<CanvasGroup>().blocksRaycasts = false;
  43. }
  44. public void OnEndDrag(PointerEventData eventData) {
  45. if (parent == null) {
  46. this.transform.position = startPosition;
  47. this.transform.SetSiblingIndex(placeholder.transform.GetSiblingIndex());
  48. } else {
  49. this.transform.SetParent(parent);
  50. }
  51. GetComponent<CanvasGroup>().blocksRaycasts = true;
  52. Destroy(placeholder);
  53. }
  54. }