- Home /
How to detect clicks from other objects in one script?
The basic way to a click is if(Input.GetMouseButtonDown(0)) but how do you detect a click from another object in one script. That way you don't need to make multiple scripts. Is there actually a way to do that? Thanks, I'm new to Javascript :)
what do you mean by basic way , and it only uses one script
Answer by yashpal · Oct 24, 2014 at 11:53 AM
Hello markzareal, You can use ray casting to detects the click events here is the documentation link of ray casting. Raycast
You can detect object by it's tag or name then ray hit something.
You just want to make one script to detect clicks.
Edited:
Here is some code you can use it's not tested.
void Update() { if(Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (collider.Raycast(ray, out hit, 100.0F))
{
if( hit.collider.gameObject.name == "YourGameObjectName")
{
//Perform action here.
}
//Or use
if(hit.collider.CompareTag("YourGameObjectTag"))
{
//Perform action here.
}
}
}
}
Thanks! I kind of get it now but I just don't get how to actually use raycast.hit, could you just give me an example of how to detect object's click by its name or tag? Thanks
Answer by 767_2 · Oct 24, 2014 at 11:57 AM
void Update () {
if (Input.GetMouseButtonDown (0)) {
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit)) {
if (hit.collider.tag=="something"){
//doSomething
}
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220613165836im_/https://answers.unity.com/themes/thub/images/avi.jpg)