How to get a rayhit to detect tags?

I can’t figure it out. I am trying to get something along the lines of if(rayhit.Tag == “Bob”)

1 Answer

1
  • a ray hits a collider
  • a collider is attached to a gameObject
  • a gameObject has the name and tag

.

Debug.Log( "Ray hit (name) : " + hit.collider.gameObject.name );
Debug.Log( "Ray hit (tag) : " + hit.collider.gameObject.tag );

example :

#pragma strict

function Start() 
{
	
}

function Update() 
{
	if ( Input.GetMouseButtonDown(0) )
	{
		CastRay();
	}
}

function CastRay() 
{
	var hit : RaycastHit;
	
	var castRayFrom : Ray = Camera.main.ScreenPointToRay( Input.mousePosition );
	
	if ( Physics.Raycast( castRayFrom, hit, Mathf.Infinity ) )
	{
		Debug.DrawLine( Camera.main.transform.position, hit.point, Color.red, 0.5 );
		
		Debug.Log( "Ray hit (name) : " + hit.collider.gameObject.name );
		Debug.Log( "Ray hit (tag) : " + hit.collider.gameObject.tag );
	}
}

Further information : 26 _ Raycasting Basics - YouTube

Thanks! I tried something similar before but now it works.