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

Can't get name of 2D clicked object

Discussion in 'Scripting' started by UniversalGesture, Oct 19, 2019.

  1. UniversalGesture

    UniversalGesture

    Joined:
    May 29, 2017
    Posts:
    125
    I want to get the name of the gameobject I clicked. I attached a box collider 2d to it but it still doesn't print out.
    This is the method called on left click :

    void CastRay() {
    Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    RaycastHit2D hit = Physics2D.Raycast (ray.origin, ray.direction, Mathf.Infinity);
    if (hit) {
    Debug.Log (hit.collider.gameObject.name);
    }
    }


    Thanks in advance
     
  2. Madgvox

    Madgvox

    Joined:
    Apr 13, 2014
    Posts:
    1,315
    ScreenPointToRay
    creates a 3D ray (has a z component).
    Physics2D.Raycast
    expects a 2D ray (no z component). There is no concept of intercepting a 3D ray on the 2D collider in Physics2D. Instead you should use
    Physics2D.OverlapPoint
    along with
    ScreenToWorldPoint
    (or raycast against a Plane and get the world point that way).
     
  3. UniversalGesture

    UniversalGesture

    Joined:
    May 29, 2017
    Posts:
    125
    I tried this but it returns Null

    void CastRay() {
    Vector2 mouse_position = Camera.main.ScreenToWorldPoint(Input.mousePosition);
    Collider2D hit = Physics2D.OverlapPoint(mouse_position);

    if (hit)
    {
    Debug.Log("Hit" + hit.transform.name);
    }
    else
    {
    Debug.Log(hit);
    }
    }
     
  4. Madgvox

    Madgvox

    Joined:
    Apr 13, 2014
    Posts:
    1,315
    If you're using a perspective camera, then you need to pass in your camera's Z offset to the vector you pass to ScreenToWorldPoint.
     
  5. UniversalGesture

    UniversalGesture

    Joined:
    May 29, 2017
    Posts:
    125
    Could you please show me how.
     
  6. UniversalGesture

    UniversalGesture

    Joined:
    May 29, 2017
    Posts:
    125
    Also the camera is in orthographic mode not perspective.
     
  7. Madgvox

    Madgvox

    Joined:
    Apr 13, 2014
    Posts:
    1,315
    Ensure that the overlap position is what you expect it to be. You can use the Debug.DrawLine or Debug.DrawRay methods for this purpose. If it is, then make sure that you've configured your object correctly, and you're actually clicking on what you think you're clicking on, and that the object has a collider, and is under the mouse.