I’m using a GUITexture with a crosshair bitmap. I’d like to be able to show the crosshair over a position in the scene (unlike a lot of crosshairs that are positioned in the center of the screen, this one needs to move). This is the code inside Update:
var screenPos = Camera.main.WorldToScreenPoint(transform.position);
var guiPos : Vector2 = GUIUtility.ScreenToGUIPoint(Vector2(screenPos.x, /Screen.height -/ screenPos.y));
I figured I need to convert the world position to screen coords, then screen to GUI, and use the result to adjust the GUITexture position. But no such luck. I’m getting an exception on the ScreenToGUIPoint line:
InvalidOperationException: Operation is not valid due to the current state of the object
System.Collections.Stack.Peek ()
UnityEngine.GUIClip.Clip (Vector2 absolutePos)
UnityEngine.GUIUtility.ScreenToGUIPoint (Vector2 screenPoint)
Does my script even look close to what it should? I used a GUITexture so the crosshair always looks the same (rather than as a game object that would be too small if it were far away). Is there a better way?
I haven’t used GUITextures at all except to check what it’s all about when I just got Unity, but if I’m not mistaken - they use screen coordinates.
Now, this is really confusing, and I think the documentation is wrong, since in reality GUITextures need values between (0,0) and (1,1)… Which is viewport space. Not screen space. Try using WorldToViewportPoint() instead.
var crossTexture: GameObject;
function Update ()
{
var screenPos = Camera.main.WorldToViewportPoint(transform.position);
crossTexture.transform.position.x = screenPos.x;
crossTexture.transform.position.y = screenPos.y;
}
I’ve added a small scene that uses this, and it seems to work… Move the game object and you’ll see the texture move as needed.