Children of cloned GameObject remaining despite trying to destroy them


I’m in the process of making a game where you protect an igloo from enemies that you shoot with snowballs that stick to them.

When you shoot an enemy with a snowball the enemy becomes the parent of that snowball which is how the snowball sticks.

My problem is, I am trying to implement spawners that create enemies from 1 enemy GameObject by instantiating clones, however, if I shoot an enemy, then the next clone that spawns in will also have that snowball attached to it. The next enemy after that however, will not.

This is the code that generates a new enemy in the spawner (the following code has GameObject (1st occurrence) or enemy behaviour (rest of the occurrences) in angle brackets where I’ve inserted an @ symbol because the forums won’t display that for some reason :

public GameObject enemy;
public List<GameObject>@ enemies;

void Start()
    enemies = new List<GameObject>();
    spawnPoint = transform;

private void spawnEnemy(int i)
    enemies[i].GetComponent<EnemyBehaviour>@().enabled = true;
    enemies[i].GetComponent<EnemyBehaviour>@().agent.enabled = true;
    enemies[i].GetComponent<EnemyBehaviour>@().health = 2;

    Instantiate(enemies[i], spawnPoint.position, spawnPoint.rotation);


    for (var p = enemies[i].transform.childCount - 1; p >= 0; p--)
        if (enemies[i].transform.GetChild(p).gameObject.tag == "Snowball")


That last if statement is meant to destroy the children of the enemy i.e. the snowballs but doesn’t work. It’s not a matter if the tag not being correct because even if I delete all children the head of the enemy (which is also a child of the enemy) gets deleted but the snowballs still don’t

Any help would be appreciated - thanks!

I think you are looking into the problem the wrong way, I might be wrong but thats what I understood from your code.

How exactly are you figuring out which enemies[i] are active and how are you deactivating them?

If you are simply destroying the gameObjects (which I suppose is true by checking out how you are destroying the snowballs) you are probably indexing the wrong enemy after the enemy[0] is destroyed because after that enemy[1] becomes enemy[0] in the “enemies” list.

My recommendation would be:
• Make the enemy prefab a private SerializeField in this spawner script
• Make the enemy script control the snowball collision and make himself attach the snowball as a child AND know how many snowballs are attached to him
• On destroy, the enemy should reduce the count of spawned enemies from the spawner by one.

Hope it helps.