- Home /
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?
Answer by whydoidoit · Jun 22, 2012 at 05:57 PM
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;
}
$$anonymous$$ike, any idea why it is doing this? From the code it should only work when the object is in the camera view, right?
Nah, it does that on the viewport point when the object is behind you...
The above fix works, thanks, but it seems a little band-aidy... are there any other ways to fix it? Would rearranging the scene work somehow? or any other way?
Nope - getting a viewport point from a world point will return a coordinate that projects the Z onto the screen from either direction - you kind of need it to work that way in some circumstances.
Your answer
![](https://koobas.hobune.stream/wayback/20220613073139im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
using GUI scrollView for multiple onGUI functions 0 Answers
GUI opacity. 1 Answer
Setting Scroll View Width GUILayout 1 Answer
GUI Not updating 1 Answer
turn off items from GUI 0 Answers