- Home /
Instantiate GUI Text at world position
Hi I know that this topic already exists, but I tried everything that was posted in the other threads to solve this and it didnt work.
I want to instantiate a GUI text "+10" at the Screen position of a gameobject.
Here is the GUI text:
heres the code, attached to the gameobject:
Vector3 pos = myCam.WorldToScreenPoint (gameObject.transform.position);
pos.y = pos.y/Screen.height;
pos.x = pos.x/Screen.width;
GameObject.Instantiate (Score_Text, pos, Quaternion.identity);
It almost works but the text isnt exactly where the gameobject is. Its under the gameobject and either right from it, or left from it, depending on the Gameobjects screen position.
Du you have Ideas to solve this? Thanks.
Answer by robertbu · May 12, 2014 at 02:55 PM
There are two issues here. First, GUIText lives in Viewport space, so you need to use WordToViewportPoint() to make the conversion. The second (potential) problem, is that your anchor is the upper left of the text. Given your current settings this line:
Vector3 pos = myCam.WorldToViewportPoint(transform.position);
Would place the upper left corner of the text at the same position as your game object. If you want it centered at that point, change the Anchor to 'Middle Center'.
Answer by HotPhone · May 13, 2014 at 11:06 AM
Ok so I changed the guitext, it seems logical to make it center.
But WorldToViewportPoint still didnt work.
my old code:
Vector3 pos = myCam.WorldToScreenPoint (gameObject.transform.position);
pos.y = pos.y/Screen.height;
pos.x = pos.x/Screen.width;
GameObject.Instantiate (Score_Text, pos, Quaternion.identity);
gives the same results as:
Vector3 pos = myCam.WorldToViewportPoint(transform.position);
GameObject.Instantiate (Score_Text, pos, Quaternion.identity);
Why is it wrong? Everywhere I see this answer but the text isnt exactly at the objects screenpoint. Its like 20% off, its not even at the edge of the object. Maybe because my gameobject is a flattened sphere? Cant upload a screenshot right now it looks kinda like this:
SPHERE SPHERE2
+10
+10
EDIT: It works perfectly if the gameobject is near the camera. The further away the gameobject is, the bigger the offset of the text.
Your answer
Follow this Question
Related Questions
GUIText Instantiation and Update the Instantiated Text. C# 1 Answer
GUIText Instantiation to show at Asteroid position 0 Answers
find GUIText 1 Answer
Change The GuiText.text by code 1 Answer
GUITextures not lining up correctly 2 Answers