- Home /
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:
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)
Answer by idbrii · Sep 27, 2014 at 03:29 PM
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
Answer by ziv03 · Dec 07, 2013 at 07:42 PM
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");
}
}
Your answer
Follow this Question
Related Questions
Using raycast to determine if player is grounded. 1 Answer
RaycastHit2D problem with PolygonCollider2D 2 Answers
Raycasting only works when close to an object 0 Answers
Physics.Raycast If/Else Problem 0 Answers
Physical shots 3 Answers