Search code examples
unity-game-engineinstance

Respawn an enemy prefab after its destroyed


var respawn : Transform;
var dead : boolean = false;

function OnTriggerEnter(theCollision : Collider)
{
   if(theCollision.gameObject.name=="Spotlight") 
   {
     Destroy(gameObject);
     Debug.Log("Dead");
     dead = true;

   }
}


function Respawn()
{

    if(dead == true)
    {
       Instantiate(respawn, Vector3(0,0,0), Quaternion.identity);
    }

}

I'm having trouble getting my enemies to re-spawn, at the moment I have just the one enemy following me around. I'm trying to re-spawn his after he collides with my spotlight.

I have a prefab Enemy that I want to use to create more instances of Enemy once it gets destroyed.

I'm pretty sure my code above is destroying the prefab itself and thus cannot create any more instances but I'm not sure how to just destroy an instance of a prefab. The code above is attached to my enemy.


Solution

  • As I said in my comment, you need to keep track of the time since the enemy died, and the best place to do that is in your respawner object. Here is an example implementation of it:

    Respawner.js

    #pragma strict
    
    var enemyToSpawn : Enemy;
    var respawnTime : int = 10; //In seconds.
    private var dead : boolean = true;
    private var deadTime : int = 0; //Time the enemy died, keep at 0
    private var nextRespawn : int = 0; 
    
    private function Respawn() {
        var enemy : GameObject = GameObject.Instantiate(enemyToSpawn.gameObject, transform.position, transform.rotation);
        enemy.GetComponent(Enemy).respawner = this;
    }
    
    function Update() {
        if (Time.time >= nextRespawn && dead) { //If the time is due and the enemy is dead
            Respawn(); //create a new enemy
            dead = false; //and tell our script it is alive
        }
    }
    
    function EnemyDied(theEnemy : Enemy) {
        dead = true;
        deadTime = Time.time;
        nextRespawn = Time.time+respawnTime;
        GameObject.Destroy(theEnemy.gameObject);
    }
    

    Enemy.js

    #pragma strict
    
    public var respawner : Respawner; // The respawner associated with this enemy
    
    function OnTriggerEnter(collision : Collider) {
        if (collision.gameObject.name.Equals("Spotlight")) {
            respawner.SendMessage("EnemyDied", this); //Tell the respawner to kill us
        }
    }
    

    Of course your enemy class will have anything else necessary to be an actual enemy, and your respawner could have an effect. This is just an example and shouldn't be blindly copy-pasted.