Physics.Linecast - how to get tag of collisioned object

Hey,

In one Unity tutorial I found this script:

	var hit : RaycastHit;
	
	//Check if there's collision inbetween turrent and target
	if(Physics.Linecast(transform.position, target.position, hit))
	{
		if(hit.collider.gameObject.tag != "Player")
		{
			print("Item in the way: "+hit.collider.gameObject.name);	
			return false;
		}
		else
		{
			print("Player detected");	
			return true;
		}
	}

I tried to run this script, but it doesn’t work properetly becouse it never prints “player detected”.

I wanted to get know why it’s happening so I’ve added this line of code:

print("tag: "+hit.collider.gameObject.tag);

and then, I received error:

So I check in script Manual Physics.Linecast function.
And I found of it takes only 2 first arguments, but not “RaycastHit” variable.
So maybe that’s why it doesn’t save in this variable anything…

But how can I get know tag of object which raycast collision with?

That error means that your RaycastHit has not registered a collision, so there’s no tag to access. Where are you placing this extra print line? It should be within the main if statement so it only runs if a hit has been detected.
Does the code return the “Item in the way” message? If it’s getting that far, it might simply be that you haven’t set the tag of the object to Player (I know that’s a basic error, but I’ve made sillier mistakes)

Hm…Ok, that was my mistake, I print this message after if statement.

I set the tag to Player for Player object(main camera and also graphic).
And in fact, it’s working but only sometimes.

When I came really close to the object and jump, then I receive “Player detected”…

Edit:
And yes - it message “item in the way…”. It has problem only with detecting player

Look again… the fomatting makes it easy to miss, but there are two variants (overloads) of Physics.Linecast(), one with and one without a RaycastHit argument. Just so you know :slight_smile: