Evans Belloeil
Evans Belloeil

Reputation: 2503

Unity GUI Label show twice for no reason

I'm working on an application where several GUI Label display names of planes.

And here's the result :

enter image description here

The problem is, if I rotate my camera by 180 °, those label are here, like there is a point symmetry :

enter image description here

So my label appear twice, once on the plane, which is good, and a second time, behind the camera.

I check if my script was not added twice, but there is no problem, more strange, if I look from an above view, the problem just disappear :

enter image description here

I have no idea where this can come from, here's my code, who is attached to every plane :

void OnGUI()
{
    if (showInfos)
    {

        Rect r = new Rect((Camera.main.WorldToScreenPoint(gameObject.transform.position)).x+25, Camera.main.pixelHeight - (Camera.main.WorldToScreenPoint(gameObject.transform.position)).y+25, 75f, 75f);

        GUI.Label(r, gameObject.transform.root.name);

    }
}

Upvotes: 0

Views: 599

Answers (1)

Rotem
Rotem

Reputation: 21947

You are drawing the labels whether or not they are in the view frustum or not.

From Camera.WorldToScreenPoint (emphasis mine):

Screenspace is defined in pixels. The bottom-left of the screen is (0,0); the right-top is (pixelWidth,pixelHeight). The z position is in world units from the camera.

You need to check if the Z value of the screen point is negative or positive (I don't know which one is in front of cam and which one is behind it, I don't use Unity), and according to that decide if it needs to be rendered or not.

void OnGUI()
{
    if (showInfos)
    {
        var pt = Camera.main.WorldToScreenPoint(gameObject.transform.position);
        if (pt.z > 0) //or < 0, no idea.
        {
            Rect r = new Rect(pt.x + 25, Camera.main.pixelHeight - pt.y + 25, 75f, 75f);
            GUI.Label(r, gameObject.transform.root.name);
        }
    }
}

Upvotes: 1

Related Questions