Playername in 3D World

Hello everyone i want to show GUILabel on playerobject

i use this code to get playername

RaycastHit hit;

if(Physics.Raycast(transform.position + new Vector3(0,0.6f,-1.6f),transform.TransformDirection(Vector3.forward),out hit)){	
	if(hit.collider.tag == "BlueTeamTrigger" || hit.collider.tag == "RedTeamTrigger" || hit.collider.tag == "Trigger"){
	Debug.Log( "mouse is over object " + hit.collider.transform.parent.gameObject.name);
	name = hit.collider.transform.parent.gameObject.name;
	ShowPosition = hit.collider.transform.position;
	Showit = true;

now onGUI()

if(Showit == true){
//INeed code to drawname next/up the object
}

Try the [docs][1] [1]: http://docs.unity3d.com/Documentation/ScriptReference/Camera.WorldToViewportPoint.html

2 Answers

2

As your object is in 3d space and OnGUI is 2D screenSpace. you have to use Camera.WorldToScreenPoint to get the x,y position on screen.

So to get position on screen:

Camera mainCam = GameObject.FindGameObjectWithTag("MainCamera").camera;

//convert world coordinates to screen coordinates
Vector3 screenPos = mainCam.WorldToScreenPoint(hit.collider.transform.parent.position);

//reverse y coordinates
float posY = screenPos.y;
posY = Screen.height - screenPos.y; // to reverse the y-coord
screenPos.y = posY;

void OnGUI(){
   if(ShowIt){
      GUI.Label(new Rect(screenPos.x, screenPos.y, 150, 40), "name here");
   }
}

Thank You Its works iwant to make raycast Thicker to get the name who around the RayCast hit

You could also use GUIText found in the Rendering menu. It adds essentially a 3D object to the scene that contains text. You then have this follow the player and switch the text to their name. I’ve done something similar to this before with success.