Question by
JackalsGekko · Nov 11, 2016 at 08:33 AM ·
c#raycastnullreferenceexception
Raycast / Null Reference Exception
Hello, I have this code for a school project and I'm really a beginner in programming. It returns a null reference exception whenever I put it:
if (hit.collider.CompareTag ("Player") && hit2.distance == 0) {
Debug.Log ("Youdead");
}
It's from a bigger code:
void Raycasting(){
Debug.DrawLine (sightStart.position, sightEnd.position, Color.magenta);
RaycastHit2D hit = Physics2D.Raycast (new Vector2 (sightEnd.position.x, sightEnd.position.y), new Vector2 (-1, 0));
RaycastHit2D hit2 = Physics2D.Raycast (new Vector2 (sightEnd.position.x, sightEnd.position.y), new Vector2 (1, 0));
Debug.DrawLine (new Vector2 (sightStart.position.x, sightStart.position.y), hit.point, Color.blue);
Debug.DrawLine (new Vector2 (sightStart.position.x, sightStart.position.y), hit2.point, Color.green);
if (hit.collider.CompareTag ("Player") && hit2.distance == 0) {
Debug.Log ("Youdead");
}
Do you have any solution to correct the Null Reference Exception?
Thanks.
Comment
You should check "hit.collider" for null before using it. If the ray didn't hit anything, there is no collider.
Your answer
Follow this Question
Related Questions
C# object reference not set to an instance of an object CS86 0 Answers
Scripting Errors 1 Answer
(Raycasts) C# Why am I shooting myself? 0 Answers