- Home /
How to parent a GUI text to current game object
I am trying to do something slightly convoluted and my inexperience with Unity is proving my task to be very difficult.
I have several spheres in my scene and I want a GUItext to appear over each one when the player hovers the mouse over it. Essentially when the sphere is being hovered over I need to make the GUItext visible and parent it to the sphere that the mouse is hovering over, and I need the text the GUItext is displaying to match the name of the sphere.
All this could easily be done in the inspector, but unfortunately most everything in the scene is being created dynamically, so that throws a wrench into things. Any guidance would greatly appreciated.
Oh, and I'm doing all of this in C#.
Test
Answer by Eric5h5 · Jul 20, 2011 at 01:26 AM
You can't parent GUIText objects to anything, because they use viewport space, whereas 3D objects use world space. (Well, technically you can parent them, but it's useless because of the incompatible coordinates.) Use a script with WorldToViewportPoint (see here for an example).
Very true! I was thinking of 3d Text when I left that comment; my bad.
3D text isn't a bad idea though, since it can be parented to allow natural movement tracking and rotation, and the size comes natural with perspective.
You rarely want text labels to be affected by rotation, size, etc., because they frequently aren't readable that way.
Thanks for the help guys, I've gotten most of the kinks worked out, currently slim$$anonymous$$g down WorldToViewPortPoint so I only use what I need to. Its a really handy script that I had no idea existed.
Answer by thekoop · Jul 20, 2011 at 12:37 AM
If you're doing it in script, you can just use transform.parent = TheGameObject.transform
simple as that really
But if the script is attached to the sphere, wouldn't that make the sphere the child of the GUItext?
when you instantiate the GUIText in the sphere's script, assign the resulting object to a variable. Then set that objects parent to be the sphere:
variable = Instantiate(TheGUIText);
variable.transform.parent = transform
Answer by Blendwolf · Dec 10, 2020 at 05:47 PM
You can vary easily just change the canvas render mode from "screen space" to "world Space" when the canvas and text are attached under the game object:
Your answer
Follow this Question
Related Questions
Rotate similar child objects around own origin 2 Answers
Distribute terrain in zones 3 Answers
Destroying an object from its script. 1 Answer
Script to add script to all children 1 Answer
Make dynamically a list of GuiText's 1 Answer