WorldToScreenPoint is giving me a wrong X position?

I want to have a Unity GUI button float over an instantiated Game Object.

I have parented a Canvas and it’s button to the prefab and have attached the follow script to the button (and filled the correct variables), but it positions the button entirely in the wrong position. What have I done wrong? Is this code correct? I have tried using both WorldToViewportPoint and WorldToScreenPoint, but I am given a wrong X position.

My canvas covers the whole screen and my button sits in the middle by default.

var characterObject 	: GameObject;
var button 		: GameObject;
var camera		: Camera;

function Start()

function ObjectToScreenPosition()
	var buttonPosition : Vector3 = camera.GetComponent(Camera).WorldToScreenPoint(CharacterObject.transform.position);
	button.GetComponent(RectTransform).anchoredPosition = buttonPosition;

The solution to this was that my canvas of the button I wanted to move was not set to Screen Space - Overlay.

On line 13, try the following instead:

button.GetComponent(Transform).position = buttonPosition;

hmm, I’m not really happy with this solution, but it works I guess. Surely there’s a more elegant way to approach this. Well, at best it might give you some ideas how to resolve the issue. The snippet you posted contained script errors for me, so I renamed things a bit.

var m_characterObject : Transform;
var m_button : GameObject;
var m_camera : Camera;

function Update()

function ObjectToScreenPosition()
  var buttonPosition : Vector3 = m_camera.WorldToScreenPoint(m_characterObject.position);
  m_button.GetComponent(Transform).localPosition = Vector3(
    buttonPosition.x - (m_button.transform.parent.GetComponent(Canvas).pixelRect.width / 2),
    buttonPosition.y - (m_button.transform.parent.GetComponent(Canvas).pixelRect.height / 2),

My problem was the same, but I found a very easy solution (even with “scale with screen size”)


        Vector3 viewPos = Camera.main.WorldToViewportPoint(anchorPoint.position);

        GetComponent<RectTransform>().anchorMin = new Vector2(viewPos.x , viewPos.y );
        GetComponent<RectTransform>().anchorMax = new Vector2(viewPos.x , viewPos.y );