Search Unity

  1. Unity 6 Preview is now available. To find out what's new, have a look at our Unity 6 Preview blog post.
    Dismiss Notice
  2. Unity is excited to announce that we will be collaborating with TheXPlace for a summer game jam from June 13 - June 19. Learn more.
    Dismiss Notice
  3. Dismiss Notice

Question RaycastHit collider is always null

Discussion in 'Physics' started by CrashCZ, Dec 4, 2022.

  1. CrashCZ


    Sep 17, 2017
    I'm running this code to detect when player clicks on certain areas on the screen.

    Code (CSharp):
    2. private void Update()
    3.     {
    4.         if(Input.GetMouseButtonDown(0))
    5.         {
    6.             var worldPoint = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    7.             var hit = Physics2D.Raycast(worldPoint,;
    9.             print(hit.collider == null ? "no object hit" :;
    10.         }
    11.     }
    The areas have an Image component and a PolygonColldier2D attached. However the code always prints "no bject hit" no matter where I click. What am I missing?
  2. MelvMay


    Unity Technologies

    May 24, 2013
    This is a misuse of raycast using it to detect if a point is overlapping a 2D collider. Not simply because using a degenerate direction vector of zero is silly but also because queries such as this only detect inside colliders when Physics2D.queriesStartInColliders is true (set in the physics settings).

    You should use OverlapPoint instead. If this doesn't work then you need to check the position you're getting from the camera conversion and that it is indeed at the position of the collider. Not using Orthographic camera mode can cause it to be not where you expect for instance.

    Also, an image component is UI and has no effect on physics so it's irrelevant. Another thing to note is that the results RaycastHit2D has a bool operator so you can do "if (hit) { }". :)