1
\$\begingroup\$

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 enemy
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. Any help is appreciated.

\$\endgroup\$
1
  • \$\begingroup\$ We can't really help you debug your code. Step through it. \$\endgroup\$ Commented Mar 28, 2014 at 17:12

2 Answers 2

1
\$\begingroup\$

With only the given information I would assume one of a few scenarios is happening here:

  1. Something very mysterious because you provided very little information

  2. Your player is on the enemy layer and subsequently the ray immediately hits the player

  3. You are not setting up your EnemyLayer variable correctly.

To filter a Raycast based on layer you need to set up a layer mask. A layer mask is the result of bitshifting (>>) the layer numbers and combine multiple layer masks into a final layer mask using the binary OR operator (|).

int layer1 = 3;
int layer2 = 5;
int layermask1 = 1 << layer1;
int layermask2 = 1 << layer2;
int finalmask = layermask1 | layermask2; //variable to use as the Raycast() layermask parameter

Given your specific code, we are only working with one layer it looks like so your code might look something like this assuming you've set up the enemy layer on the first available custom layer which would be layer 8.

int enemyLayer = 8;            
int enemyMask = 1 << enemyLayer;            
//int layerMask = enemyMask; //No need for setting up a final mask because we only have one layer to check

RaycastHit2D hit = Physics2D.Raycast(transform.position, Vector2.right, enemyMask);

To comment on your edit:

The above should help you resolve the issue with not needing to disable your player collider. The null reference exception is likely due to the fact that you aren't colliding anything. You need to actually check if hit.collider is null as hit will return information even if it doesn't hit.

\$\endgroup\$
1
\$\begingroup\$

First of all your code is not correct:

if(hit!=null){
    print (hit.collider.tag);
}

Raycast will ALWAYS return not null object. And you ALWAYS need to check hit.collider for null. It can be found easy in manual:

http://docs.unity3d.com/ScriptReference/Physics2D.Raycast.html

\$\endgroup\$

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.