I create a game that need user to drag and drop in a box. I used Grid Layout
to arrange the Button
s in a box. But when dragged, the Button
is below all other elements. I already tried change to SetAsLastSibling()
and SetParent()
but it does not work.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public class UIDrag : MonoBehaviour, IDragHandler, IEndDragHandler, IPointerDownHandler
{
Vector3 startPosition;
Vector3 diffPosition;
GameObject canvas_;
public Vector2 originalPos;
private bool ObjOnTop;
public static Transform saveObj;
public void OnDrag(PointerEventData eventData)
{
transform.position = Input.mousePosition - diffPosition;
//Debug.Log(Input.mousePosition);
}
public void OnEndDrag(PointerEventData eventData)
{
if (ObjOnTop)
{
transform.SetParent(saveObj);
}
else
{
transform.position = originalPos;
}
}
public void OnPointerDown(PointerEventData eventData)
{
startPosition = transform.position;
diffPosition = Input.mousePosition - startPosition;
EventSystem.current.SetSelectedGameObject(gameObject);
EventSystem.current.currentSelectedGameObject.transform.SetParent(canvas_.transform);
EventSystem.current.currentSelectedGameObject.transform.SetAsFirstSibling();
Debug.Log("start drag " + gameObject.name);
}
private void OnTriggerStay2D(Collider2D input)
{
if (input.gameObject.CompareTag("Drop"))
{
ObjOnTop = true;
saveObj = input.gameObject.transform;
}
}
private void OnTriggerExit2D(Collider2D input)
{
if (input.gameObject.CompareTag("Drop"))
{
ObjOnTop = false;
}
}
void Start()
{
canvas_ = GameObject.Find("Canvas");
originalPos = transform.position;
}
void Update()
{
}
}