World/Screen Space Mix Up

I am trying to write a code where, when a Vector3 position is given to the ActivateBar function, a progress bar appears on the screen positioned in Screen Space to appear as if it is at that world position. I have written the following code to do so:

public class LoadingBar : MonoBehaviour 
{
	float timeStart;
	float progress = 0;
	Vector3 barPos;
	Vector2 screenPos;
	Vector2 size = new Vector2(50,10);
	public Texture2D progressBarEmpty;
	public Texture2D progressBarFull;
	Ray mouseRay;
	   	
	private bool barActive;
	
	void Start()
	{
		barActive = false;
	}
	
	void OnGUI()
	{
		if (barActive)
		{		
		    GUI.DrawTexture(new Rect(screenPos.x, screenPos.y, size.x, size.y), progressBarEmpty);
		    GUI.DrawTexture(new Rect(screenPos.x, screenPos.y, size.x * Mathf.Clamp01(progress), size.y), progressBarFull);
		}
	} 
	
	void Update()
	{
		if (barActive)
		{
		screenPos = camera.WorldToScreenPoint(barPos);
	     	progress = (float)((Time.time - timeStart) * 70 * Time.deltaTime);
		}
	}
	
	public IEnumerator ActivateBar(Vector3 buildingPosition)
	{
		barPos = buildingPosition;
		timeStart = Time.time;
		progress = 0;
		barActive = true;
		yield return new WaitForSeconds (1);
		barActive = false;
		progress = 0;
	}
}

The problem is, not only does the bar appear in a weird position that is only close to where I would want it to be, but I wanted the bar’s position to be based on world space so that when the camera scrolls, say, left, the bar moves right to “follow” it’s location in world space. Instead when scrolling, the bar moves wildly and I cannot figure out why. Can anyone help?

When using WorldToScreenPoint you need to invert the y-axis in my experience

screenPos.y *= -1;
screenPos.y += Screen.height;

But I have a better solution:

var text : GUIText;
var cube : Transform;
function OnGUI(){
	text.transform.position = camera.WorldToViewportPoint(cube.position);
}

Using WorldToVIEWPORTPOINT, you can ignore inverting, and you can also use the .z axis to hide the text when the object is behind the object.

like:

if(text.transform.position.z < 0){
text.enabled = false; // or something...
}

EDIT: Woops wrote in .javascript!