0

I'm trying to find the name of the tile which is being hit on. But for the debug.log() line of the code, it keeps saying

NullReferenceException: Object reference not set to an instance of an object

Below is my code:

    if (Input.GetMouseButtonDown(0)) 
    {
        Ray ray = _camera.ScreenPointToRay(Input.mousePosition);
        RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction);
        Debug.Log(hit.transform.name);
     
    }
Pri Mar
  • 105
  • 1
  • 6

1 Answers1

1

Try checking if you hit something first

if (Input.GetMouseButtonDown(0)) 
{
    Ray ray = _camera.ScreenPointToRay(Input.mousePosition);
    RaycastHit2D hit = Physics2D.Raycast(ray.origin, ray.direction);
    if(hit.collider != null)
    {
        Debug.Log(hit.transform.name);
    }
 
}
Becon032
  • 51
  • 1
  • 5