Raycast, click on instance: Object reference not set to an instance of an object


I want to click on a instance(cloned). But when I click on it gives me the following error:

Object reference not set to an instance of an object

This is the code of the raycast:

if (Input.GetMouseButtonDown (0)) {
        RaycastHit2D hit;
       hit = Physics2D.Raycast (Camera.main.ScreenToWorldPoint (Input.mousePosition), Vector2.zero, 100f);
        Collider2D c = hit.collider;
        if (hit.collider.gameObject.GetInstanceID () == gameObject.GetInstanceID ()) {...}

I tried many work arounds but nothing happens, it keeps throwing the same error.
can you help me please?? thank you!

Sorry about this, but I forgot to add a BoxCollider component to my object. I feel embarrased now…hehe…
Thank you guys!

Maybe the null reference is because the raycast dosent hit anything.
First of all you should create a check against a null collider.

if(c != null){do something...} 

It’s a good practice to prevent error’s and to help debugging.

When you raycast you should convert the mouse position to a ray, using ScreenPointToRay instead of ScreenToWorldPoint.

p.s Camera.main.ScreenPointToRay(Input.mouseposition).origin will give you a vector3.