Canvas to World Coordinates Works in Editor but Not in Builds

Hi I have a cursor over some sprite objects, that cursor is part of the UI canvas, when the user presses the arrow keys the selector will move to another object in world space.

I use this code to calculate where the cursor should go.

public static Vector2 WorldToCanvasSpace(this Canvas canvas, Vector3 worldPosition)
    {
        Vector2 viewportPosition = Camera.main.WorldToViewportPoint(worldPosition);
        return new Vector2((viewportPosition.x * Screen.width) - (Screen.width / 2), 
            (viewportPosition.y * Screen.height) - (Screen.height / 2));
    }

My function works in the editor, it places the cursor at the correct “worldPosition” that I pass, but when I build the game the cursor is not in the correct position.

*When I say cursor I don’t mean the mouse cursor… just to be clear.

Any help would be delightful, thanks in advance.

Try:

Vector3 viewport_position = Camera.main.WorldToViewportPoint(worldPosition);
RectTransform canvas_rect = canvas.GetComponent<RectTransform>();
return new Vector2((viewport_position.x * canvas_rect.sizeDelta.x) - (canvas_rect.sizeDelta.x * 0.5f), (viewport_position.y * canvas_rect.sizeDelta.y) - (canvas_rect.sizeDelta.y * 0.5f));

and set it to anchoredPosition.