- Home /
Question by
ItzPorkchop · May 03, 2021 at 05:28 PM ·
unity 2dparent-childcards
Unable to set object as child
I followed a tutorial for most of this, but somewhere along the line where I changed the card from an Image to an Image with children, the drag and drop code no longer works. I have a DropZone with a rigidbody and a boxcollider and the card also has both. Theoretically, when the card is released over the dropzone, it should become its child. This is not the case. using System.Collections; using System.Collections.Generic; using UnityEngine;
public class DragDrop : MonoBehaviour
{
public GameObject Canvas;
private bool isDragging = false;
private bool isOverDropZone = false;
private GameObject dropZone;
private GameObject startParent;
private Vector2 startPosition;
private void Awake()
{
Canvas = GameObject.Find("Main Canvas");
}
void Update()
{
if(isDragging)
{
transform.position = new Vector2(Input.mousePosition.x, Input.mousePosition.y);
transform.SetParent(Canvas.transform, true);
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
isOverDropZone = true;
dropZone = GameObject.Find("DropZone");
}
private void OnCollisionExit2D(Collision2D collision)
{
isOverDropZone = false;
dropZone = null;
}
public void StartDrag()
{
startParent = transform.parent.gameObject;
startPosition = transform.position;
isDragging = true;
}
public void EndDrag()
{
isDragging = false;
if(isOverDropZone)
{
transform.parent = dropZone.transform;
}
else
{
transform.position = startPosition;
transform.SetParent(startParent.transform, false);
}
}
}
Comment