UI item touches another UI item

Hello,

I usually use sprites to see if objects collide. But since I am using a UI Button now and a UI text I’m not sure how to detect if they touch each other on mouse up. Usually I would use a boxcollider2d and check for collison. That doesnt seem to work now.

My button is a trash bin and I want to be able to drag my UI text object to the trash bin and when I let go it should delete the text if the text is touching the bin.

How do I check if they touch each other? I use Eventsystem for drag and for revealing the bin when the text is pressed. Is there a “we are touching each other” in eventsystem that I can use or what is the best way to go about this?

Respectfully, Ellen

One possible way would be to determine the bounding rectangle for each object and convert them to screen coordinates.

You could also choose to look only at the mouse position instead of checking the dragged object’s entire bounding box. Then you could rely on raycasting (either checking all ray hits, or making the dragged object not be a raycast target so that you only need to check the first hit).

There might also be better options that haven’t occurred to me; I haven’t dealt with this exact problem before. I’m fairly surprised that you had a solution that worked for sprites but it doesn’t work for text.

It will be easiest if you still use colliders to detect collision. In addition to the colliders, you will probably either need to attach a Ridigbody2D to one of them so you can use the OnTrigger/OnCollision functions, or you can instead check if 2 specific colliders are touching when you need to using draggedObjectCollider.IsTouching(trashCollider)

Consider the ondrop event

Other option is you could test the distance between your trash bin and your dragged object so when you let go, if that distance is <= a certain amount, you assume it’s going in the recycle bin.

1 Like

Thank you for all your alternatives, I will check all of them and see if I can get them working.

Edit: Did some research on Ondrop and it was a fitting match. Added it to the bin. Code for reference:

using UnityEngine;
using UnityEngine.EventSystems;

public class deletebutton : MonoBehaviour, IDropHandler
{

    public void OnDrop(PointerEventData eventData)
    {
        Destroy(transform.root.gameObject);
    }
}