用 children 实例化游戏 object

instantiate game object with children

我有一个 GameObject(EnemyProducer),它实例化了另一个 GameObject(EnemyFormation),它有几个 children(实际敌人)。

但是,当我实例化 EnemyFormation Gameobject 时,它没有任何 children!

EnemyFormation 是一个预制件,具有所有必需的 children。

这是它的样子:

这是实例化 EnemyFormation 的 EnemyProducer 代码:

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;
        }
    }
}

第一次实例化可能会成功,因为它从编辑器中克隆了预制件,但随后您将新克隆的预制件重新分配给 enemyFormation。当所有敌人(children)被摧毁时(假设你使用的是Destroy())然后enemyFormation将不包含child。下次你 Instantiate(enemyFormation) 你应该得到一个没有 children 的 gameObject 因为它不再是编辑器的预制件(它是由你重新分配的)。

抱歉,我必须删除之前的答案。反正都是错的。