- Home /
Working with RayCast
I am working on a project and I am trying to use RayCast to get input values. I got two scripts, one is working perfectly and that is being called on Update() method, but this script is being called on OnMouseDown() method (Code below):
void OnMouseDown() {
if (Input.GetMouseButtonDown (0)) {
RaycastHit hit;
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
float maxDis = 15000;
if (Physics.Raycast(ray,out hit,maxDis)) {
Debug.Log(hit.collider.name+" is "+hit.distance+" far away from the screen");
if (hit.collider.name == "Cube" && GameObject.FindGameObjectsWithTag("needToBePlaced").Length < 1) {
GameObject tempBuild = (GameObject)Instantiate (building, Input.mousePosition, Quaternion.identity);
tempBuild.name = "NeedToBePlaced";
tempBuild.tag = "needToBePlaced";
tempBuild.GetComponent<BuildingCreationHandler> ().isPlaced = false;
}
}
}
}
I have my camera. My camera has two children attach to it. Cube and Cube (1). It picks those collides up, but when I click another GameObject that is on the same tier as the camera, it doesn't execute the Debug.Log method and I am not understanding why it isn't picking it up.
Answer by tpusch · Dec 14, 2015 at 12:37 AM
The reason it is working for the children of the camera but not for other objects in the hierarchy is because of how OnMouseDown works. If you wanted your camera to be able to tell any object that was clicked you could move that block of code into the Update() function. Or alternatively put the result of your click into the OnMouseDown() of the cube itself.
Wow, thanks. It didn't dawn on me that the script only picked up "On$$anonymous$$ouseDown" if that elements or the children of the elements where clicked. I was more focused on I must've done something with the Ray.
Your answer
Follow this Question
Related Questions
Mouse pos + raycast 1 Answer
How to make a ball stay in the air longer when force is added? 1 Answer
Changing a Variable within the same script 0 Answers
Multiple Cars not working 1 Answer