Using ScreenPointToLocalPointInRectangle outside of BaseEventData

I would like to create an object that follows my mouse cursor in the new UnityGUI.

As there is no event that would give me a continuous stream of data whenever the pointer hovers over the RectTransform (there is IMoveHandler / OnMove but that doesn’t get triggered, not sure what is it for), I need to calculate the position myself.

I tried:

RectTransformUtility.ScreenPointToLocalPointInRectangle(GetComponent<RectTransform>(), Input.mousePosition, Camera.main, out localPoint)

But that doesn’t seem to work, so what other approach can I take to get this done? Mind you, I don’t have any BaseEventData (PointerEventData etc.) using this approach as this is not part of the event system.

I would really like to know this too.
If there is any other way of calculating the local point in a RectTransform, independently of the event system.

Try passing null instead of Camera.main.
Worked for me. No idea why it should be so. :roll_eyes:

2 Likes
Canvas myCanvas = GetComponent<Transform>().root.GetComponent<Canvas>();
Vector2 pos;
RectTransformUtility.ScreenPointToLocalPointInRectangle(myCanvas.transform as RectTransform, Input.mousePosition, myCanvas.worldCamera, out pos);
//if we want to follow the mouse we do this:
transform.position = myCanvas.transform.TransformPoint(pos);

Take a look at: