Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Get coordinates of clicked position on Object

Discussion in 'Scripting' started by ki_ha1984, Nov 18, 2014.

  1. ki_ha1984

    ki_ha1984

    Joined:
    Aug 24, 2014
    Posts:
    111
    Hi,

    I would like to ask, how i can get the coordinates of my mouse over on object where i clicked.
    In example i have a cube and i clicked on one of its face, how i can get the transform.position ?
    Not the cube position?

    Thank you.
     
  2. Suddoha

    Suddoha

    Joined:
    Nov 9, 2013
    Posts:
    2,824
    Using a raycast, you can use an overload which allows you to get additional information (via the 'out RaycastHit' parameter) about the object you hit, the position the hit occured at, the normals etc.
     
  3. RSG

    RSG

    Joined:
    Feb 20, 2013
    Posts:
    93
    I'm not sure what you mean by transform.position. If you mean the point in the surface of the cube where you clicked, then you can use a raycast:

    Code (CSharp):
    1. var position = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    2. RaycastHit hit;
    3. Physics.Raycast(ray, out hit);
    4. if(hit.rigidbody != null)
    5. {
    6.     Debug.Log ("hit: " + hit.point);
    7. }
    8.  
     
    Suddoha likes this.
  4. Suddoha

    Suddoha

    Joined:
    Nov 9, 2013
    Posts:
    2,824
    But there's missing the part of the creating the ray or simply use Camera.main.ScreenPointToRay in order to initialize the ray, that should work aswell.
     
    Sephirossss likes this.