- Home /
UI elements following GameObjects (3d world)
After a deep research in this forum (found about 4 topics on this matter ) I am unable to make this running and i Don't figure out why ......... I'm very confused.
The ojective here is very simple : I have an Scene where 3d Objects will spawn , under certain circustances I want to Track the position of the object to the Screen or Viewport (not sure wich will fit) and render an UI element at the center of the object ( could be a text or an image , would like to play with this to mix 2d with 3d ).
Description of the Scene: For make things simpler i made a Prefab called "POINTER" , its a CANVAS with Space Overlay and Scale with Screen Size ( for multi resolutions purpose).. Then inside this Canvas I've got a simple text UI element All positions to 0 and anchors to 0,5 all. width and height are 30. ( i prooff tested to manually drag & drop this and It works and by default its placed in the midle of the screen ..... and if i tweak the transform of the text X and Y during play i can see it moving over the screen like im suposed to do by code, giving it the position of the gameobject to be over).
CODE:
void Capoprueba(GameObject refobject)
{
Vector3 objt_position = refobject.transform.position;
Vector3 viewport = Camera.main.WorldToScreenPoint(objt_position);
viewport.y = -viewport.y;
// Debug.Log(viewport);
GameObject CanvasLabel = Resources.Load("POINTER") as GameObject;
GameObject pl = Instantiate(CanvasLabel,viewport,Quaternion.identity) as GameObject;
}
I did a bit testing about CanvasLabel.GetComponent().transform.localPosition = viewport; nothing seems to work :(_
Why not just create the UI canvas in worldspace rather than as a screen overlay? That's kind of what it's for.
Answer by Flaring-Afro · May 09, 2016 at 06:03 PM
Create a world space canvas for each text/icon. Make the parent of each canvas the gameobject it moves with. Then, you will want to make a script for each canvas and in the update method, make its rotation match the camera's rotation, unless you want the text to be seen sideways depending on camera position.
First of all thank you for replying; Yes I ' ve basically set the Canvas to Overlay to auto-adjust the UI - elements to the viewport whatever resolution is, and the behaviour was correct until now.
So giving this situation where more UI elements are co$$anonymous$$g I take your point as a viable solution; let's say I have to manually adjust the canvas Size ELements i Already have depending on the target device resolution and then will try to do the same for the upco$$anonymous$$g UI elements spawned.
I will come with the solution / or frustation under this way, Thank you !!
Your answer
Follow this Question
Related Questions
I can't get a button to register a touch and execute. 0 Answers
How to adjust the screen resolution? 0 Answers
Scroll View Null Reference error 0 Answers