- Home /
Detect if UI element is over Gameobject
I want to be able to detect if a UI element is over a gameobject and return true if it is. I need it so that if any part of the UI element is touching the gameobject then it returns true.
I was originally using cursor position but that did not work as something the user can drag and drop the item to the gameobject position and it does not register.
This should return as true.
This should return as false.
I cannot fathom how this isn's a more discussed issue. It is literally drag and drop functionality.
Answer by Stactic_Games · Aug 12, 2020 at 07:40 PM
use on trigger enter
OnTriggerEnter()
{
//event here
}
plz help on my question
If you are using 2D, you actually need to use OnTriggerEnter2D.
Create a gameobject.
Add a CircleCollider2D to that gameobject
Add a script to make it follow your mouse
On that script add OnTriggerEnter2D and use the documentation to get the behaviour you want
On trigger enter does not get activated by UI items over gameobjects.
Why do you need to use UI items ? A 2D Sprite would be much easier to handle. Add a scipt to make it follow your mouse. UI is, by definition, not made to interract physically with gameobjects :)...
using UnityEngine;
using System.Collections;
public class $$anonymous$$ouse$$anonymous$$ove2D : $$anonymous$$onoBehaviour {
private Vector3 mousePosition;
// Update is called once per frame
void Update () {
if (Input.Get$$anonymous$$ouseButton(1)) {
mousePosition = Input.mousePosition;
mousePosition = Camera.main.ScreenToWorldPoint(mousePosition);
transform.position = mousePosition;
}
}
void OnTriggerEnter2D (Collider2D col)
{
if(col.transform.tag == "mytag")
{
// DO YOUR STUFF
}
}
}
It needs to be UI the way I have it. I have a tab that contains multiple tools represented as UI icons like in the image above. The user then drags and drops these icons onto where said tool should be used in the scene.
Using 2D srpites would mean I would loose all the canvas scaling for different devices that I have working. Along with me needing to rewite a lot of work to implament it.
Answer by danielos1996 · Aug 14, 2020 at 10:03 AM
I'm finding it hard to even get the world position of a moving UI object. I think if I could get that I could atleast make progress.