WorldToScreenPoint in Update/OnGUI: Bad Performance

Hey all,

I have a simple script which takes the position of the current game object and overlays a 2D texture in its Screen point position.

The issue I am having is it is chewing the main thread! I’m seeing a normal thread time of 12.1ms without the WorldToScreenPoint. With it, it can jump as high as 127ms, but idles around 78ms.

Any suggestion for an alternative?

My Code:

This can be in either Update () or OnGUI () - But OnGUI () results in much worse performance (as expected).

screenPos = Camera.main.WorldToScreenPoint(transform.position);
screenPos.y = Screen.height - screenPos.y;
screenRect = new Rect
			(
			screenPos.x - (prefabManager.planetGUIWindowTexture.width / 2) - (Camera.main.transform.position.y),
			screenPos.y - (Camera.main.transform.position.y), 
			prefabManager.planetGUIWindowTexture.width, 
			prefabManager.planetGUIWindowTexture.height
			);

Here is the code creating the texture:

void OnGUI () {
		GUI.DrawTexture(screenRect, prefabManager.planetGUIWindowTexture);		
}

I managed to solve this.

isVisible = child.renderer.IsVisibleFrom(Camera.main);

		if (isVisible) {
        screenPos = Camera.main.WorldToScreenPoint(transform.position);
		screenPos.y = Screen.height - screenPos.y;
		screenRect = new Rect
			(
			screenPos.x,
			screenPos.y, 
			prefabManager.planetGUIWindowTexture.width, 
			prefabManager.planetGUIWindowTexture.height
			);
	}
}

Storing the result of IsVisibleFrom in a cached variable solved the extra CPU time. Seems the functions were executing asynchronously and causing leaks.