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()
{
ObjectToScreenPosition();
}
function ObjectToScreenPosition()
{
var buttonPosition : Vector3 = camera.GetComponent(Camera).WorldToScreenPoint(CharacterObject.transform.position);
button.GetComponent(RectTransform).anchoredPosition = 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()
{
ObjectToScreenPosition();
}
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),
0);
}