Search Unity

Resolved Determine clicked position with OnMouseDown

Discussion in 'Scripting' started by Capricornum, Aug 26, 2020.

  1. Capricornum

    Capricornum

    Joined:
    Feb 1, 2018
    Posts:
    22
    I believe that for the event OnMouseDown some Raycasting is happening behind the scenes. So is it possible to access the point of where any gameObject/collider implementing OnMouseDown was clicked without doing another raycast but by accessing that "Behind the scenes Raycasting"? Something like:

    void OnMouseDown() {Vector3 clickedPosition = eventData.Position;}

    Thank you very much.
     
  2. Adrian

    Adrian

    Joined:
    Apr 5, 2008
    Posts:
    1,066
    OnMouseDown
    is outdated and might be removed at some point in the future. There's also now way to access the raycast that was used to fire the event.

    Instead, I suggest you work with the event system:
    - If there isn't already an "EventSystem" game object in your scene, create one with the GameObject » UI » Event System menu
    - Add the Physics Raycaster or Physiscs 2D Raycaster component to your camera
    - Implement the
    IPointer*
    interfaces you need in your scripts (e.g. IPointerClickHandler), the provided PointerEventData object will have all the information, including the raycast
     
    PraetorBlue and Capricornum like this.
  3. Capricornum

    Capricornum

    Joined:
    Feb 1, 2018
    Posts:
    22
    Thank you so much Adrian! I will try your approach.