Make image follow your cursor

Hello.

I’ve made a really simple inventory with PiDi’s tutorial but I don’t really know how would I nest my item icon (UI image) on specific position (let’s say next to the cursor) when I’m dragging it around my inventory. Right now I’m setting the local position of my icon with this script:

if(draggingItem)
    {
        Vector3 mousePos = (Input.mousePosition - GameObject.FindGameObjectWithTag("Canvas").GetComponent<RectTransform>().localPosition);
        dragItemIcon.GetComponent<RectTransform>().localPosition = new Vector3(mousePos.x + 15, mousePos.y - 15, mousePos.z);
    }

The problem is that the icon is not moving as fast as the mouse and sometimes it prevents me from dropping the item to one of the slots (because I’m actually clicking at the icon image, not the slot).

It looks like this: Imgur

I’d be very grateful for any bit of help!

Your code is OK, I don’t think you can move the image to follow the cursor using something really different.

Maybe the problem with your code is that it’s slow. I guess that code is being executed inside an Update function, so you’re calling:

GameObject.FindGameObjectWithTag("Canvas").GetComponent<RectTransform>()

and:

dragItemIcon.GetComponent<RectTransform>()

every frame. GetComponent is not really slow, but you can save those references in a private variable instead of getting them each time. FindGameObjectWithTag IS slow, it goes through the objects on your hierarchy and checks the tag of each one until one has the “Canvas” tag. If you’re always searching the same object on the scene just find it once in some Awake or Start method and use the reference in the future.