- Home /
How to lock my object after drag and dropped in specific position?
Hello! I'm having a harsh time figuring this out! I was possible to code to drag and drop my object and stick it in to my slots, but the object was able to be dragged again when I clicked it. Is there a way to lock the object when it is placed in the slot?
Drag and Drop Script
public static GameObject itemBeingDragged;
Vector3 startPosition;
Transform startParent;
public void OnBeginDrag(PointerEventData eventData)
{
itemBeingDragged = gameObject;
startPosition = transform.position;
startParent = transform.parent;
GetComponent<CanvasGroup>().blocksRaycasts = false;
transform.SetParent(transform.root);
}
public void OnDrag(PointerEventData eventData)
{
transform.position = Input.mousePosition;
}
public void OnEndDrag(PointerEventData eventData)
{
itemBeingDragged = null;
if (transform.parent == startParent || transform.parent == transform.root)
{
transform.position = startPosition;
transform.SetParent(startParent);
}
GetComponent<CanvasGroup>().blocksRaycasts = true;
}
Slot Script
public GameObject item
{
get
{
if (transform.childCount > 0 && transform.childCount < 2)
{
return transform.GetChild(0).gameObject;
}
return null;
}
}
public void OnDrop(PointerEventData eventData)
{
if (!item)
{
DragHandeler.itemBeingDragged.transform.SetParent(transform);
}
}
You could try to freeze the objects position once it's in the right place by using https://docs.unity3d.com/ScriptReference/RigidbodyConstraints.FreezePosition.html , like for example:
Slot Script
public GameObject item
{
get
{
if (transform.childCount > 0 && transform.childCount < 2)
{
return transform.GetChild(0).gameObject;
}
return null;
}
}
public void OnDrop(PointerEventData eventData)
{
if (!item)
{
DragHandeler.itemBeingDragged.transform.SetParent(transform);
DragHandler.itemBeingDragged.getComponent<RigidBody>().constraints = RigidbodyConstraints.FreezePosition;
}
}
or alternatively add some bool variable to the object itself that can be checked by the Drag and Drop script to check if the object can be moved or not.
Answer by JonPQ · Aug 15, 2019 at 01:02 AM
if your object is 2d, e.g. image. Set image.interactable to false If its an object you are raycasting to, change it's layer to one that is not raycast checked after its dropped.
Answer by uzum4ki82 · May 13, 2020 at 09:05 PM
Please I have the same problem and I don't know what code use.
Please tell me where o whose can help me
Your answer
![](https://koobas.hobune.stream/wayback/20220612210550im_/https://answers.unity.com/themes/thub/images/avi.jpg)