Script destroying both gameobjects instead of just one.

So, my problem is I have a collider gameobject (cube) that is a child of the bush I want to destroy. When I run this script (pressing E) it destroys all gameobjects instead of just one. Please help, I am very confused.

using UnityEngine;
using System.Collections;

public class Collect : MonoBehaviour {

    public GameObject UIText;

    void Start() {
        UIText.SetActive (false);
    }

    void OnTriggerEnter() {

        UIText.SetActive (true);

    }

    void OnTriggerExit() {

        UIText.SetActive (false);

    }

    void Update() {

        if (Input.GetKeyDown (KeyCode.E)) {
            Ray ray = Camera.main.ScreenPointToRay (new Vector2 (Screen.width / 2, Screen.height / 2));
            RaycastHit hitInfo;

            if (Physics.Raycast (ray, out hitInfo, 3.5f)) {
                if (hitInfo.transform.tag == "Bush") {
                    UIText.SetActive(false);
                    Destroy(gameObject);
                    Destroy(hitInfo.transform.gameObject);
                }
            }
        }

    }
}

Thank you very much!

Destroy(gameObject) destroys the object this script is on. Destroy(hitInfo.transform.gameObject) destroys the object hit by the Raycst, so there are already two objects being destroyed by this code.

But from your innitial sentence, there is a third object, which is a child of one of these two, also getting destroyed. This is due to the fact that Destroy() not only destroys the object itself, but the whole hierarchy below this object, so if you have an object that should not be destroyed, then you should not parent it to an object that should be destroyed (or set its parent to null before destroying the other object)

1 Like

So, you misunderstand what I am saying, I have 2 bushes. I have a cube collider (other object, child) around one bush and the other. When I run the script and I press E on a bush it destroys both bushes