Trying to create a script that will make a parent object delete when all of its children are gone

I’ve created a prefab “Spell” object with several Spheres inside that travel toward the player. I’m trying to make it so that when all of the Spheres are gone, the Spell will delete. Here’s the script I’ve made to try to make it work:

using UnityEngine;
using System.Collections;

public class DestroyOnCollision : MonoBehaviour {
    private GameObject sp;
    void Start(){
        sp = transform.parent.gameObject;
    }
    void OnCollisionEnter(Collision collision) {
        if (sp.transform.childCount == 1) {
            Destroy (sp);
        }
        Destroy(gameObject);
    }
}

What this does is it checks to see if the current Sphere is the last one, and if so, deletes the Spell. Otherwise, it deletes the Sphere. This works, but if the last two or more Spheres contact an object at the same time, they are both destroyed without destroying the Spell. How could I fix this script or do it in a different way?

This should go in the scripting section. Also please use code tags.

There are many ways to handle this, but here is a simple way:

Add a variable called RefCount to the Spell
Set this to the number of sphere automatically OnAwake
Add a method to spell called Kill() that decreases RefCount by one and destroys Spell if RefCount = 0
Call Kill() on collision and destroy sphere

Regards,
Sajid

Thank you for telling me. I’ve edited it and will remember in the future.

Thanks. I was able to make it work using that.

Great. Glad I could help.