gravvy

Untitled

Jul 12th, 2015
278
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.03 KB | None | 0 0
  1. using UnityEngine;
  2. using UnityEngine.UI;
  3. using System.Collections;
  4. using UnityEngine.EventSystems;
  5.  
  6. public class Draggable : MonoBehaviour, IBeginDragHandler, IDragHandler, IEndDragHandler {
  7.  
  8.     public Transform parentToReturnTo = null;
  9.     public Transform placeholderParent = null;
  10.  
  11.     GameObject placeholder = null;
  12.  
  13.     public enum Table { PLAYER, ENEMY }
  14.     public Table typeOfItem = Table.PLAYER;
  15.  
  16.     public void OnBeginDrag(PointerEventData eventData) {
  17.         Debug.Log ("OnBeginDrag");
  18.  
  19.         placeholder = new GameObject();
  20.         placeholder.transform.SetParent( this.transform.parent );
  21.         LayoutElement le = placeholder.AddComponent<LayoutElement>();
  22.         le.preferredWidth = this.GetComponent<LayoutElement>().preferredWidth;
  23.         le.preferredHeight = this.GetComponent<LayoutElement>().preferredHeight;
  24.         le.flexibleWidth = 0;
  25.         le.flexibleHeight = 0;
  26.  
  27.         placeholder.transform.SetSiblingIndex( this.transform.GetSiblingIndex() );
  28.  
  29.         parentToReturnTo = this.transform.parent;
  30.         placeholderParent = parentToReturnTo;
  31.         this.transform.SetParent( this.transform.parent.parent );
  32.  
  33.         GetComponent<CanvasGroup>().blocksRaycasts = false;
  34.     }
  35.  
  36.     public void OnDrag(PointerEventData eventData) {
  37.  
  38.         this.transform.position = eventData.position;
  39.  
  40.         if(placeholder.transform.parent != placeholderParent)
  41.             placeholder.transform.SetParent(placeholderParent);
  42.  
  43.         int newSiblingIndex = placeholderParent.childCount;
  44.  
  45.         for(int i = 0; i < placeholderParent.childCount; i++) {
  46.             if(this.transform.position.x < placeholderParent.GetChild(i).position.x) {
  47.  
  48.                 newSiblingIndex = i;
  49.  
  50.                 if(placeholder.transform.GetSiblingIndex() < newSiblingIndex)
  51.                     newSiblingIndex--;
  52.  
  53.                 break;
  54.             }
  55.         }
  56.  
  57.         placeholder.transform.SetSiblingIndex(newSiblingIndex);
  58.  
  59.     }
  60.  
  61.     public void OnEndDrag(PointerEventData eventData) {
  62.         Debug.Log ("OnEndDrag");
  63.         this.transform.SetParent( parentToReturnTo );
  64.         this.transform.SetSiblingIndex( placeholder.transform.GetSiblingIndex() );
  65.         GetComponent<CanvasGroup>().blocksRaycasts = true;
  66.  
  67.         Destroy(placeholder);
  68.     }
  69.  
  70. }
Add Comment
Please, Sign In to add comment