Taimoor Rana Taimoor Rana - 2 months ago 23
C# Question

instantiate game object with children

I have a GameObject(EnemyProducer) that instantiate another GameObject(EnemyFormation) which has several children (actual enemies).

However, when i instantiate EnemyFormation Gameobject it does not have any children!

EnemyFormation is a prefab with all the required children.

This is how it looks like:

enter image description here

Here is the EnemyProducer code that Instantiates EnemyFormation:

public class EnemyProducer : MonoBehaviour {
EnemyFormation enemyGroup;
Transform enemyFormationTransform;
public float speed;
float boundary, currentY;
bool goingDown = true;
public GameObject enemyFormation;

// Use this for initialization
void Start () {
// Create enemyformation
enemyFormation = Instantiate (enemyFormation);
enemyFormation.transform.parent = transform;
enemyGroup = enemyFormation.GetComponent<EnemyFormation>();
boundary = Camera.main.orthographicSize;
enemyFormationTransform = enemyFormation.transform;
}
void Update () {

// if all enemies are killed, create a new one
if (!enemyGroup.hasEnemy ()) {
enemyFormation = Instantiate (enemyFormation);
enemyFormation.transform.parent = transform;
enemyGroup = enemyFormation.GetComponent<EnemyFormation>();
enemyFormationTransform = enemyGroup.gameObject.transform;
}
}
}

Answer

The first Instantiation may be successful because it cloned the prefab from the Editor but then you reassigned the newly cloned prefab to the enemyFormation. When all enemies (children) were destroyed (assume that you were using Destroy()) then enemyFormation would contain no child. Next time you Instantiated(enemyFormation) you were expected to get a gameObject without children because it were not the prefab from the Editor anymore (it was replaced by you).

Sorry I have to delete the previous answer. It is wrong anyway.