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:

What line is the error on?
– meat5000I'm having the same issue. Have you made any progress with this? It works just fine when not using physics2D.
– CabooskaIn 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)
– robertbu