0
\$\begingroup\$

I want to drag a game object out of a UI. Currently, I am instantiating a game object on top of the UI(on an upper sorting layer), and adding code to make it able to drag the object. However, Unity cannot detect if the mouse is over the object. The object has a box collider 2D and the scene has an event system.

public void OnPointerEnter()
{
    mouseEnter = true;
    Debug.Log("mouse enter");
}

public void OnPointerExit()
{
    mouseEnter = false;
}
void Update()
{
    if(Input.GetMouseButton(0) && mouseEnter)
    {
        Vector3 pos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        transform.position = new Vector3(pos.x, pos.y, 0);
    }
}

The code is attached to the item I want to drag. It is being properly instantiated on top of the UI element, but it can't be dragged.

Some searching suggested that the UI element might be blocking the raycast...but I don't truly understand how this works or how to fix it.

Maybe the way I am doing this is wrong, so is there any solution?

\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

You need another variable to indicate whether the object is dragged or not.

And when dragging, mouseEnter is unrecoginzed.

bool dragging;

void Update()
{
    if(Input.GetMouseButton(0))
    {
        if(mouseEnter)
        {
            dragging = true;
        }
    }
    else if(dragging)
    {
        dragging = false;
    }

    if(dragging)
    {
        Vector3 pos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        transform.position = new Vector3(pos.x, pos.y, 0);
    }
}
\$\endgroup\$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .