- Home /
How to destroy a object when dragged into an empty canvas.
I am making a game which involves a lot of drag and drop. I have some objects that the player has to drag into the object slot. How do I destroy the object if the player drags it outside the slot or somewhere randomly on the canvas. This is the code I have used. public class dragDrop : MonoBehaviour, IDragHandler, IBeginDragHandler, IEndDragHandler { Image image; CanvasGroup canvasGroup; Vector2 initPosition; void Awake(){ Time.timeScale = 1; image = GetComponent<Image>(); canvasGroup = GetComponent<CanvasGroup>(); initPosition = transform.position; } public void OnBeginDrag(PointerEventData eventData) { canvasGroup.alpha = 0.5f; canvasGroup.blocksRaycasts = false; } public void OnDrag(PointerEventData eventData) { transform.position = eventData.position; } public void OnEndDrag(PointerEventData eventData) { canvasGroup.alpha = 1f; canvasGroup.blocksRaycasts = true; } }
Answer by perf401 · Feb 05 at 02:58 PM
Not sure what's the best solution, but when i personally had this problem, i approached it like this: Get data what's under mouse. Use OnPointerEnter method/event for that. It should be on both ObjectSlot and Canvas Interface. I created static class to hold variable of what's currently under my mouse.
public static class MouseData
{
public static object objectMouseIsOver;
}
OnPointerEnter event method example:
OnPointerEnter(ObjectSlot slot)
{
MouseData.objectMouseIsOver = slot;
}
Example of my Inventory : MonoBehavior, IPointerEnterHandler
public void OnPointerEnter(PointerEventData eventData)
{
MouseData.objectMouseIsOver = eventData.pointerCurrentRaycast.gameObject;
Debug.Log(MouseData.objectMouseIsOver);
}
Basically, when you drop object to a objectSlot, check if objectMouseIsOver equals to slot or interface. If it's interface, Destroy(objectThatYouAreDropping).
Your answer
