Search code examples
c#unity-game-enginespritemouse

Unity 3D, How can I detect if mouse is over a 2D Sprite even if the Sprite is not visible


I work with the Unity3D game engine and I stumbled across this problem. When I try to check if the mouse is over a sprite, I can do so by using this callback.

private void OnMouseOver()
{
    // Do Something
}

But if the mouse is not directly over the sprite, this method won't work. Are there any alternatives?

The Orange sprite is the sprite I want to detect, but the blue circle makes it to not detect the mouse (This doesn't look really good, I am not an artist, but I should make things clear I hope)


Solution

  • If you want to know what object(s) are underneath your mouse click, use this:

    Example - put it in your update:

    if (Input.GetMouseButtonDown(0))
    {
        var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        var hits = Physics2D.GetRayIntersectionAll(ray, 1500f);
    
        foreach (var hit in hits)
        {
            print($"Mouse is over {hit.collider.name}");
        }
    }
    

    For performance reasons, you may want to use: