I’m using WorldToScreenPoint to place a label UI over each enemy. There is only one UI shown in the heirarchy, but I see two. They are located at polar opposite positions. I observe the second label when I pan around. Ideas?
Vector3 v3 = Camera.main.WorldToScreenPoint(enemyList*.transform.position);*
RectTransform rTrans = enemyLabelList*.GetComponent();*
rTrans.position = v3;
I’m aware that this is rather old question but since it is still not answered and someone may still make use of this I decided to answer it here anyway.
So first of all let me clarify what is happening. You do not see TWO ui elements. This “second one” you’re observing behind your back is actually the same one you could see in front.
It is happening because of calculation done by WorldToScreenPoint() function. This function is transforming 3D world position into 2D position on the screen so if you have your 3D position directly behind you ( enemy behind the camera ), the calculated 2D position will be on the screen in front of your camera facing back to the enemy. This is creating the illusion that you see 2 UI labels instead of 1.
There is easy fix for that. Even though you’re calculating 2D screen position it is stored in Vector3 so all you have to do is add a simple check if “z” part of the vector is below 0 and eventually multiply it by -1.
For your code it would be:
Vector3 v3 = Camera.main.WorldToScreenPoint(enemyList*.transform.position);*
if (v3.z <0 )
v3 *=-1;
RectTransform rTrans = enemyLabelList*.GetComponent();*
rTrans.position = v3;
Hope it’s useful to anyone!