Search Unity

Gameobject under mouse position with "Queries start in colliders" disabled.

Discussion in '2D' started by rheirman, Oct 11, 2019.

  1. rheirman

    rheirman

    Joined:
    Sep 30, 2019
    Posts:
    2
    For my project it's very convenient to have the project setting "Queries start in colliders" disabled. This does however have the consequence that the following (commonly used) method of getting a game object under the mouse position doesn't work:

    Code (CSharp):
    1.  
    2. var hitInfo = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero)
    3. //then use hitInfo for retreiving the object.
    This doesn't work because the ray starts in the collider of the gameObject, and therefore doesn't collide due to the project setting I use.

    Now I'm struggling to find another way of detecting game objects under the mouse that is as powerful (i.e. works for any collider and doesn't need explicit coding to handle each collider). Does anyone have suggestions, or should I just accept that this isn't possible with the project setting used?
     
  2. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    1,966
    This is 2D so if you want to know if a collider overlaps a point simply use OverlapPoint.

    I still don't understand why everyone's first call is to use Raycast and try to perform a degenerate zero-distance raycast "into" the screen. There must also be a discovery problem in the docs as these are all listed there. :)
     
    rheirman likes this.
  3. rheirman

    rheirman

    Joined:
    Sep 30, 2019
    Posts:
    2
    Wow, that makes a lot of sense! I wasn't aware of the OverlapPoint method (fairly new to Unity), and googling "unity 2d gameobject under mouse" only yielded results of people relying on the raycast. I probably shouldn't rely on google that much :).

    Thanks for the help!
     
    MelvMay likes this.
  4. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    1,966
    Don't get me wrong, I wasn't having a dig at you either sir. It's just amazing how many people try to fit Raycast into every behaviour imaginable when there's so many dedicated queries available. It's probably as you say, others devs using Raycast as a solution and Google finding it. :)