- Home /
UI - Best method for Scene UI elements
Hello,
I would like to know what the best method is in order to place Scene UI elements over the top of scene objects.
For example, I have a building that has a health script attached to it. When '_onFocus' is true on this building, I would like to show a UI Health Bar that sits above the building, as if it appears in the scene.
Originally, I would just place a 3D plane/quad within the actual scene, and have that dynamically scale with the health percentage.
But I would like to take advantage to Unity's builtin UI system. I have the Canvas with 'World Space' render mode, but how would I place a 2D UI element in Rect position with relation to my building in 3D space? Or am I going about this wrong way?
Thanks.
Answer by LK84 · Dec 29, 2016 at 10:30 AM
you can just child the canvas (World Space) containing the health bar to the respective GameObject and enter values for the RectTransform until it is in the right position relative to the Object. Additionally add a script to the canvas with has transform.LookAt(Camera.main.transform);
in the Update() Loop.
Thanks for your reply. What about scaling though? If it's actually an object in the 3D scene, then the further the camera is, the smaller the UI will be?
Yes. But isn't better to have the healtbar scaled with the apparent size of the game object (a far distant object shouldn't have a big health bar?). If you want to achieve a constant size of your healt bar just use Camera.WorldToScreenPoint(Vector3 YourGameObjectPosition)
to place the UI Element on the Canvas (which is now a root object of course)