- Home /
4.6 Gui anchoring a ui element to a Game Object
I need anchor a ui element to a gameobject like bellow. There was a feature like this on NGUI.
Answer by Lordinarius · Nov 08, 2014 at 10:07 AM
I made a workaround here is the code.
public static Vector3 GetScreenPosition(Transform transform,Canvas canvas,Camera cam)
{
Vector3 pos;
float width = canvas.GetComponent<RectTransform>().sizeDelta.x;
float height = canvas.GetComponent<RectTransform>().sizeDelta.y;
float x = Camera.main.WorldToScreenPoint(transform.position).x / Screen.width;
float y = Camera.main.WorldToScreenPoint(transform.position).y / Screen.height;
pos = new Vector3(width * x - width / 2, y * height - height / 2);
return pos;
}
Answer by Kiwasi · Nov 07, 2014 at 11:59 PM
Use a world space canvas that is a child of the GameObject.
But i will tween this Text to score label. When player gets score/coin it will be shown above of player then it will tween to score label.
This is how NGUI is working http://www.youtube.com/watch?v=lwAT8IO8v0I&list=UUQGZdUwzE8gmvgjomZSNFJg#t=449
If you want to do it the way NGUI does then I suggest you use NGUI.
Unity UI system currently does not have this functionality. The way you attach a UI element to a GameObject is by parenting. You could also create a script of your own to duplicate this functionality.
Your answer
![](https://koobas.hobune.stream/wayback/20220613171000im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Unity 4.7 - OnGUI prevent click/touch through 0 Answers
[PUN] I want people to see my GUI 2 Answers
How do I access the button component of a button in the new gui system. 2 Answers
Example of setting up a button OnClick event via scripting? 2 Answers
Unity 4.6 adding a Canvas Text onto a gameobject prefab?? -1 Answers