Search code examples
c#gameobjectunity-game-engine

Let Child GameObject Destroy Itself Issue


I have n GameObjects that are children of a mother GameObject.

Each child has its own child script attached. If I click on one child object, ALL children respond.

When the child is loaded it puts itself under the parent and I also pass a number so I can keep up with it later if I want.

Here is my script. There really isn't much to it. Anyone know what I am doing wrong?

public GameObject parentGameObject;
public int childIndex;

void Start () {
    transform.parent = parentGameObject.transform;
}

void Update () {
    if (Input.GetMouseButton(0)) {
        Die();
    }
}

public void Die () {
     Debug.Log("Child " + this.childIndex + " clicked");
     Destroy(this.gameObject);
}

Solution

  • Since this script is attached to all of your child objects, they are all checking to see if the mouse is clicked, and therefore all destroying themselves when a mouseclick is detected (since a mouse click is detected in every script).

    I would suggest having one script in the mother gameobject that uses a Raycast and attach Colliders and tag each child to detect when one of them is clicked, and then destroy the corresponding clicked object.

    It's not clear if you are in 2d but the example for it would be like so:

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            // cast a ray at the mouses position into the screen and get information of the object the ray passes through
            RaycastHit2D hit = Physics2D.Raycast(Camera.main.ScreenToWorldPoint(Input.mousePosition), Vector2.zero);
            if (hit.collider != null && hit.collider.tag == "child") //each child object is tagged as "child"
            {
                Destroy(hit.collider.gameObject);
            }
        }
    }