Weird GUI error (script included)

On screen: plane, cube(rigidbody), camera, directional light, first person standard asset.

Now add this script to an empty game container. Add cube as transform to target.

Run.

GUI appears over cube, great. Now turn around, the GUI is also behind you.

Why is this? It should only work when cube is visible right? I don’t want the GUI behind me! What am I doing wrong?

var target : Transform;

var barDisplay : float = 0; var pos :
Vector2 = new
Vector2(Screen.width/2,Screen.height/2);
var size : Vector2 = new
Vector2(100,20); var progressBarEmpty
: Texture2D; var progressBarFull :
Texture2D;

function OnGUI() {
GUI.BeginGroup (new Rect (pos.x*Screen.width,
(1-pos.y)*Screen.height, size.x,
size.y));
GUI.Box (Rect (0,0, size.x, size.y),progressBarEmpty);
GUI.EndGroup (); }

function Update () {
pos=Camera.main.WorldToViewportPoint(target.position);
print(Camera.main.WorldToViewportPoint(target.position));
}

Any idea?

Don’t display the GUI if the item is behind you using the Dot product of the positions like this:

  function OnGUI() {
        if(Vector3.Dot(target.position - transform.position, transform.forward) < 0) 
                return;
  }