- Home /
Issue with Destroy() when identifying the gameObject with a RayCast
Probably a really simple issue but I'm not seeing it. Just putting together a little Point & Click and I want an object to be destroyed when the user clicks on it with the mouse.
I'm not getting any errors and the gameObject is still there. keyBlue has no children and contains a mesh, a box collider and a custom script which is just rotating around.
function Update ()
{
if (Input.GetMouseButtonDown (0))
{
var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
var hit : RaycastHit;
if (Physics.Raycast (ray, hit))
{
var modelhit = hit.collider.renderer.transform.name;
switch(modelhit)
{
case "keyBlue":
print("I hit the Blue Key");
bBlueKey = true;
Destroy(GetComponent(modelhit));
break;
}
}
}
}
The boolean is switched to true so it is running that chunk. Thanks in advance.
Answer by Senhor de todo o Mal · Feb 11, 2011 at 04:28 PM
Try this:
function Update () { if (Input.GetMouseButtonDown (0)) {
var hit : RaycastHit;
if (Physics.Raycast (Camera.main.ScreenPointToRay (Input.mousePosition), hit))
{
if(hit.transform.name == "keyBlue"){
print("I hit the Blue Key");
bBlueKey = true;
Destroy(hit.transform.gameObject);
}
}
}
}
Damn! Very good!
I take it I was not calling the gameObject in $$anonymous$$e?
Basically, when you were calling Destroy(GetComponent(modelhit)), modelhit was the string "keyBlue", GetComponent would try to find a component named keyBlue in the current gameObject and Destroy would remove it.
Your answer
![](https://koobas.hobune.stream/wayback/20220613103847im_/https://answers.unity.com/themes/thub/images/avi.jpg)