How do you destroy respawned clones?

var respawnPrefab : GameObject;

function OnTriggerEnter(myTrigger: Collider){
    if(myTrigger.gameObject.name == "tum1-2"){//tum1-2 is a wall    	
			
        //respawns at the location of a game object tagged Respawn in the middle of the game. 
        var respawns = GameObject.FindGameObjectsWithTag ("Respawn");
			
        for (var respawn in respawns) {
            Instantiate(respawnPrefab, 
                respawn.transform.position, respawn.transform.rotation);
        }       
	
	    Time.timeScale = 1;
    }
}

This is my respawn script and it works well. When my collider gameObject hits the wall the player dies and then respawns back at the begining of the level. If the player crashes and dies again using the instantiated cloned gameObject, a new cloned object appears in my hierarchy called “FPS(clone)(clone)”. The first one was called “FPS(clone)”.

I’m trying to write a script with the expression == null and !=null but I can’t figure it out. I’m trying to figure out how to only have one instance of the cloned gameObject at anyone time. Can anyone help me with this?

I’ve read through many of the answers but I haven’t been able to apply it to my script which is straight out of the Unity API reference under respawn.

How do I destroy the previous cloned game object after respawning again and again? Can someone help me modify my script?

Thanks.

This is somewhat confusing. Let’s change the logic a little: the Respawn object will contain the prefab reference in playerPrefab, and will respawn it when its function RespawnPlayer is called. The player will suicide upon entering the death wall trigger, but will call RespawnPlayer before leaving this world.

I’m supposing that:

  • The wall named “tum1-2” is the trigger;

  • The player must die when touching it;

  • Once dead, the player must respawn at a fixed point tagged “Respawn”

1- Save this script as RespawnScript.js, attach it to the Respawn object, and drag the player prefab to playerPrefab at the Inspector:

var playerPrefab: GameObject; // drag the player prefab here

function RespawnPlayer(){
  Instantiate(playerPrefab, transform.position, transform.rotation);
}

2- Attach this script to the player:

function OnTriggerEnter(hit:Collider){
  if (hit.name == "tum1-2"){ // if player hit the wall...
    Destroy(gameObject); // it suicides
    // get the object tagged "Respawn"
    var objRespawn = GameObject.FindWithTag("Respawn");
    // get the script RespawnScript.js
    var script: RespawnScript = objRespawn.GetComponent(RespawnScript);
    script.RespawnPlayer(); // respawn a new player
  }
}