C# 2d Instantiate GUIText and lock it to position on map, not to follow camera.

Hello. I am having a really hard time trying to work with GUIText instantiation. I want the instantiate to be placed correctly just like any other GameObject instantiation, but it works too mysteriously for me. I have atleast managed to make it spawned at the correct position initially, but it still happens to follow the camera when any other movement of the camera is made. So, I want this to not happen. I want this to have its own fixed position on the game map.

Relevant code:

 public GameObject textGUI;

        void OnTriggerStay2D(Collider2D col) {
		if(col.gameObject.tag == "Food") {
			//Add to current health
			curhp += 5;
			FoodPoint();
			audio.PlayOneShot(munchFood);
			Destroy (col.gameObject);
		}
	}

	void FoodPoint() {
		Vector3 pos = Camera.main.WorldToScreenPoint(transform.position);

		pos.x = pos.x /Screen.width;
		pos.y = pos.y /Screen.height;

		GUIText obj = GUIText.Instantiate(textGUI,pos, Quaternion.identity) as GUIText;

There is more stuff that is incorrect at the moment, like passing on new information to the textGui. It is none of my concern at this moment. I just want to know how I can instantiate on the game map, not the camera. Thank you for any help.

1 Answer

1

GUIText are positioned on the screen. They don’t pay any attention to cameras or world space or the like.

Two options to solve

  • Use a TextMesh. This is a 3D component that can be positioned in world space
  • Upgrade to Unity 4.6 and use a world space canvas.

Thank you. I did hear something about a textmesh earlier. Cheers mate :) EDIT: I guess textmesh can as easily be used in 2d, right?

Yes, just get the rotation right and it will appear 2D