Respawn Destroyed GameObject(Enemy)

时间:2013-04-21 02:46:31

标签: c# unity3d

我正在写一个游戏(2D平台游戏),当玩家重生时,我正试图让敌人重生。我不能简单地重新加载关卡,因为我有一些在加载关卡时加载的对象,所以它会导致一些问题。相反,要重新生成玩家,我让它返回到它的起始位置(我处理丢失的生命和其他细节)。

玩家通过击中敌人来摧毁敌人,如下所示(在玩家的OnTriggerEnter上):

if(otherObject.CompareTag("Minion")) //hit by minion
    {
        if(hitFromTop(otherObject.gameObject)) //if player jumped on enemy
        {
            otherObject.GetComponent<Minion>().setMoving(false); //stop moving
            playSound(KillEnemySound); //play killing enemy sound
            jump();
            Destroy(otherObject.gameObject); //kill minion

        }
                    //else hurt player
    }

如你所见,我完全摧毁了敌人的物体。为了保持哪些敌人在哪里,我在创建时将它们添加到列表(存储在单独的GameObject中)。该列表在单独的敌人重生对象中创建,如下所示:

void Start ()
{
    enemyList = GameObject.FindGameObjectsWithTag("Minion");
    Debug.Log ("Adding all minions to list");
}

我试图通过列表调用一个函数来重新生成列表中所有minions的原始位置。功能如下:

public void RespawnAll()
{
    foreach(GameObject minion in enemyList)
    {
        Destroy(minion); //make sure to respawn ALL minions
    }
    Debug.Log ("Respawning all");
    foreach(GameObject minion in enemyList)
    {
        Debug.Log ("instantiating minions from list");
        Instantiate (minion, minion.GetComponent<Minion>().origPosition, Quaternion.identity);
    }
}

我知道删除所有敌人并重新制作所有敌人并不是时间最优的方法,如果这种逻辑错误或者你知道更好的方法,我会接受新的想法。

这个想法的问题是,我收到一个错误:

MissingReferenceException: The object of type 'GameObject' has been destroyed but you are still trying to access it. Your script should either check if it is null or you should not destroy the object.

似乎我在列表中添加了对现有minion的引用而不是副本。我怎样才能在原来的位置正确地重建敌人?

1 个答案:

答案 0 :(得分:2)

我接受了Jerdak的建议,而不是摧毁敌人,我禁用了它们。这样,它们仍然存在,我可以循环并重新启用所有被禁用(被杀死)的敌人。

相关问题