Search Unity

UI item touches another UI item

Discussion in 'Scripting' started by ellenblomw, Sep 18, 2019.

  1. ellenblomw

    ellenblomw

    Joined:
    Mar 4, 2018
    Posts:
    153
    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
     
  2. Antistone

    Antistone

    Joined:
    Feb 22, 2014
    Posts:
    2,836
    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.
     
  3. MSplitz-PsychoK

    MSplitz-PsychoK

    Joined:
    May 16, 2015
    Posts:
    1,278
    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)
     
  4. Brathnann

    Brathnann

    Joined:
    Aug 12, 2014
    Posts:
    7,187
    doctorpangloss likes this.
  5. ellenblomw

    ellenblomw

    Joined:
    Mar 4, 2018
    Posts:
    153
    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:

    Code (CSharp):
    1. using UnityEngine;
    2. using UnityEngine.EventSystems;
    3.  
    4. public class deletebutton : MonoBehaviour, IDropHandler
    5. {
    6.  
    7.     public void OnDrop(PointerEventData eventData)
    8.     {
    9.         Destroy(transform.root.gameObject);
    10.     }
    11. }
    12.  
     
    Last edited: Sep 20, 2019