- Home /
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
Answer by hav_ngs_ru · Jan 28, 2015 at 10:04 AM
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.
so, for continiousl button press handilng - use Get$$anonymous$$ouseButton ins$$anonymous$$d of Get$$anonymous$$ouseButtonDown (first will return true every frame while mouse button is held down, but first - only once when you press it down, but not when you hold it). And set speed to some value more about 10, to ensure you wil really see if the motion occured.
if ( Input.Get$$anonymous$$ouseButton (0)){ // << use Get$$anonymous$$ouseButton ins$$anonymous$$d of Get$$anonymous$$ouseButtonDown
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if ( Physics.Raycast (ray,out hit,100.0f)) {
Debug.Log("You selected the " + hit.transform.name);
hit.transform.position += Vector3.right * speed * time.deltaTime; // << declare public speed and set it in inspector
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613181740im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Multiple GameObjects with the same script all react but I only want one at a time. 2 Answers
Create multiple prefabs from multiple objects in the selection of the Hierarchy (Unity 5.3.5) 1 Answer
Destroying objects with the same name that are touching eachother. 1 Answer
Batching objects with Instantiate for optimization 2 Answers