Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

NullReferenceException on Unity

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);
     
    }

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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);
    }
 
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading