RaycastHit2D

Hello, I have this code:

private RaycastHit2D ray;

    private void FlyBuildingItems()
    {
            Vector3 MousePosition = Camera.ScreenToWorldPoint(Input.mousePosition);
             ray = Physics2D.Raycast(MousePosition, -Vector2.zero);

            if (Input.GetMouseButton(0))
            {
                if (ray.collider.CompareTag("Build"))
                    IsBeingDragger = true;
                }
            }
        }

It works as I intended, but when I click on an object without a collider, it gives the error “NullReferenceException: Object reference not set to an instance of an object”, the error itself does not interfere with the code in any way, but it catches the eye.
How can I fix it ?

ALWAYS the same way, ALWAYS.

How to fix a NullReferenceException error

https://forum.unity.com/threads/how-to-fix-a-nullreferenceexception-error.1230297/

Steps to success:

  • Identify what is null
  • Identify why it is null
  • Fix that
2 Likes

If you look at any code example for raycast it always makes sure that the raycast actually hit something before proceeding using an if statement. You should follow that pattern:

3 Likes

Also, don’t use a degenerate raycast (length or direction of zero) to effectively check a point. Because it’s 2D, you only need to use Physics2D.OverlapPoint and pass in the world-space position of the mouse.

It’s faster and more efficient to use the correct 2D techniques rather than stuff that’s been adapted from 3D.

1 Like