- Home /
Destroy objects by clicking on them
Hi. I want to destroy objects if they are clicked. I know that I have to use Raycasts for that. I don't want to detect clicks on a single object. I need to detect it on all objects tagged with "destroyable". So I'll also need GameObject.FindGameObjectsWithTag("destroyable"). Now I have no idea how to check all the tagged objects.
Answer by robertbu · Feb 14, 2013 at 05:34 PM
You don't have to find all game objects with the tag. As you click on something, you can check it tag. A script (untested):
function Update () {
if (Input.GetMouseButtonDown(0)) {
var ray : Ray = Camera.main.ScreenPointToRay (Input.mousePosition);
var hit : RaycastHit;
if (Physics.Raycast (ray, hit)) {
if (hit.collider.tag == "destroyable") {
Destroy(hit.collider.gameObject);
}
}
}
}
Hey, thanks, it worked great! How can I fix the mouse position to the mid of the screen? It's a first person game, so that would be useful
It would probably be best to hide the cursor:
Screen.showCursor = false;
And then use GUI to display an indicator (crosshairs) in the center of the screen. Note if you want to always cast the ray from the center of the screen, take a look at Camera.ViewportPointToRay(). Their example shows casting a ray from the center of the screen.