how to detect an gameobject on mouse click using raycast

i have multiple objects running on single script.
i want to select one object on mouse click.

if ( Input.GetMouseButtonDown (0)){ 
RaycastHit hit; 
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); 
if ( Physics.Raycast (ray,out hit,100.0f)){ 
//suppose i have two objects here named obj1 and obj2.. how do i select obj1 to be transformed 
if(hit.transform!=null) { 
transform.Translate (Time.deltaTime, 0, 0, Space.Self); 
} 
}

}

The answers given previously do not work…
pls help

Please format your code properly. Plus you can get the object that was hit with Raycast using hit.collider.gameObject so your translate line becomes: hit.collider.gameObject.transform.Translate (new Vector3(Time.deltaTime, 0, 0), Space.Self);

hey thanks for it.. it does not work.....

1 Answer

1

actualy you doind right to detect what object was picked…
but I didnt understand what are you trying to do with selected object…

transform.Translate (Time.deltaTime, 0, 0, Space.Self) - this will move selected object along X just about 0.03 units (so you cant see it). Try something like this instead:

if ( Input.GetMouseButtonDown (0)){ 
  RaycastHit hit; 
  Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); 
  if ( Physics.Raycast (ray,out hit,100.0f)) {
    StartCoroutine(ScaleMe(hit.transform));
    Debug.Log("You selected the " + hit.transform.name); // ensure you picked right object
  }
}

IENumerable ScaleMe(Transform objTr) {
    objTr.localScale *= 1.2f;
    yield return new WaitForSeconds(0.5f);
    objTr.localScale /= 1.2f;
}

hey.. thats true.. but if i continuously press the right key it should move na.

where do you want it to move? ok, I'm a user. I see 2 obkects. What I should click some of them for? In other words - when I clicked some of them - what I expect to happen?

i would want the obj1 or obj2 to move either right or left on click.

will try and let u know

it does not work......