Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

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.

share|improve this question
    
We can't really help you debug your code. Step through it. –  Grey Mar 28 '14 at 17:12

1 Answer 1

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.