How to destroy a spawned object that lies on my raycast
I have spawned cubes that I want destroyed when they are line with my raycast ray but I do not know what GameObject to put in Destroy (...).
Teacher said I need to pass Destroy(...) a GameObject instance which I can get from a RaycastHit object but I don't really know how to do this.
This is what i have so far:
     if (Input.GetMouseButtonDown(0)) {
         Ray ray = cameras.ScreenPointToRay(Input.mousePosition);
         Debug.DrawRay(ray.origin, ray.direction*5f, Color.red,2f);
         RaycastHit hit;
         bool isHit = Physics.Raycast (ray, out hit, 10f);
         if (isHit) {
         Debug.Log ("We just hit " + hit.transform.name);
         Destroy (???);
 
              I'm getting the red squiggly line under gameObject.
And doesn't gameObject refer to where the script is attached ($$anonymous$$e is attached to the FirstPerson Character) not the spawned object? Correct me if I'm wrong, I'm a newbie.
Answer by navot · Feb 18, 2017 at 01:45 AM
Whoops... Didn't check whether RaycastHit has a reference to the gameObject which is being hit, which apparently it doesn't.
gameObject on its own refers to the Object, which the script is attatched to, but when you reference something else, it can refer to another GameObject (like hit.transform refers to the other objects transform, not the transform of the FirstPerson Character)
This should work:
Destroy (hit.transform.gameObject);
Your answer