NullReferenceException with Physics2D raycast

Hi, I’m getting a error with raycasting (Physics 2D). I have this code in a Gun, but I get a NullReferenceException (Object reference not set to an instance of an object)…

This is my script:

using UnityEngine;
using System.Collections;

public class GunRaycast : MonoBehaviour {

	public Transform gunPoint;
	public Transform mirilla;

	public Vector2 mousePos2D;

	public Gun gun;

	void Awake(){
		gun = GetComponent<Gun>();
	}

	void Update () {
		mousePos2D = new Vector2(gun.screenPos.x, gun.screenPos.y);

		RaycastHit2D hit = Physics2D.Raycast(gun.transform.position, mousePos2D);

		if(hit.collider.gameObject.name == "PhysicableSquare"){
			Debug.Log ("PhysicableSquare hit");
		}
	}
}

I don’t know what I’m doing bad, so, Can someone explain me how?

Thanks.

Here a image of the structure of my game:

structure

What line is the error on?

I'm having the same issue. Have you made any progress with this? It works just fine when not using physics2D.

In my tests, I'm getting back non-null values for the 'hit' in situations where the raycast cannot succeed. In those cases, the hit.collider is null. I'm not sure if this is a Unity bug, or if there is something fundamental I'm missing about Physics2D.Raycast(). A workaround is to check both 'hit' and the 'collider'. if (hit != null && hit.collider != null)

2 Answers

2

The RaycastHit2D’s collider documentation says you can check the result directly (which uses the “implicit conversion operator converting to bool”):

RaycastHit2D result = Physics2D.Linecast(start, end, seeTargetMask);
if (result)
{
    // Find something we can hurt.
    Kill(result.transform.gameObject);
}

I think that’s clearer than checking the collider.

I don't get what idbrii means by "you can check the result directly" but where if (raycastHit != null) {... failed for me if (raycastHit) {... worked

You’re getting the NullReferenceException because the raycast returns null when there is no collider in the direction.
you can do this:

  if(hit != null)
  {
      if(hit.collider.gameObject.name == "PhysicableSquare"){
          Debug.Log ("PhysicableSquare hit");
      }
  }

I'm still getting the error :S

sorry, i edited it. hit != null and not hit != nul