- Home /
How to find an object in front of player?
I am trying to find an object that is in front of my player sprite using the following code
RaycastHit2D hit = Physics2D.Raycast(transform.position,Vector2.right,EnemyLayer);
//EnemyLayer is the layer having enemys
if(hit!=null){
print (hit.collider.tag);
}
But this is printing "player",the tag of the object on which the script is attached What am i doing wrong?
EDIT: Ok,I found out why it was printing player-because I had a big circular collider surrounding my player. Deactivating it gives me the following error
NullReferenceException: Object reference not set to an instance of an object
I have no clue what it means.
Are you absolutely sure no other objects in the scene (not just enemies) are tagged as "player"? In my usual state of lack of sleep, I end up copy/pasting objects and forgetting to change their tag. Just double check. And double check that the player is not on the EnemeyLayer. Beyond that, it doesn't make much sense, and there's not enough here to help.
Are you sure your player is not on the enemy layer? Or something like that?
Answer by NoteMEdown · Dec 06, 2018 at 12:48 AM
Change the code to
RaycastHit2D hit = Physics2D.Raycast(transform.position,Vector2.right,EnemyLayer);
//EnemyLayer is the layer having enemys
if(hit){
print (hit.collider.tag);
}
hit returns a bool, thus it will never be null. So when you type
if(hit != null)
This will always be true, and your print will always happen. When you dont hit anything, you will get a NullReferenceException.