Search Unity

how to find which object is clicked

Discussion in 'Scripting' started by jpsubbarayalu, Nov 30, 2010.

  1. jpsubbarayalu

    jpsubbarayalu

    Joined:
    Jul 13, 2010
    Posts:
    65
    Hi all,

    am having one cube object and have attached move script to cube.I have added this cube as prefab.
    Dynamically am creating object for cube prefab. Onmouse click i have to find out which cube i have clicked.

    if(Input.GetMouseButton(0)||Input.GetMouseButton(1))
    {

    var ray = Camera.main.ScreenPointToRay(Input.mousePosition);
    var hit : RaycastHit;
    if(Physics.Raycast(ray, hit))
    {
    var hitobjname=hit.collider.gameObject.name;
    if(hitobjname=="Cube(Clone)")
    {
    print("action..");
    }
    }
    }

    The above code is always entering into loop without touch the cube also..

    How to do the best way..

    Thanks
     
  2. SteveZantes

    SteveZantes

    Joined:
    Nov 29, 2010
    Posts:
    13
    Try to use this:
    if(Physics.Raycast(ray, hit))
    {
    if(hit.transform.tag=="Cube")
    {
    print("action");​
    }​
    }

    You need to assign the tag name "Cube" to the cube object. :)
     
  3. Chris-Sinclair

    Chris-Sinclair

    Joined:
    Jun 14, 2010
    Posts:
    1,326
    You can also use the OnMouseDown/OnMouseUp/OnMouseEnter/etc methods. (I don't think these work on iPhone though)
     
  4. KelsoMRK

    KelsoMRK

    Joined:
    Jul 18, 2010
    Posts:
    5,539
    Correct - these do not work in iPhone.
     
  5. jpsubbarayalu

    jpsubbarayalu

    Joined:
    Jul 13, 2010
    Posts:
    65
    Hi,

    May i know the solutions?..
     
  6. andeeeee

    andeeeee

    Joined:
    Jul 19, 2005
    Posts:
    8,768
    There's a thread here that explains how you can detect the object under the mouse using a raycast from the camera.