- Home /
Respawn destroyed object
Hi everyone I have this script where as to when i hit a trigger my enemy spawns at a random time then the enemy destroy itself at a random time. I want to respawn the enemy again so it can do this over and over again. Any Suggestions:
public class SpawnManager : MonoBehaviour {
public GameObject Enemy; // the enemy prefab
public float mytimer; // the time to wait before spawn
public float transport;// the time it has to destroy itself
private GameObject _spawndEnemy; // the enemy that was spawnd
void SpawnEnemy()
{
var enemySpawnPoint = GameObject.Find("FFEnemySpawn1").transform;
_spawndEnemy = Instantiate(Enemy, enemySpawnPoint.position, enemySpawnPoint.rotation) as GameObject;
transport = Random.Range (2,15);
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.name == "FFTrigger") {
mytimer = Random.Range(0,15);
Invoke("SpawnEnemy", mytimer);
Debug.Log("Spawn Normal");
}
}
void Update()
{
Destroy (_spawndEnemy, transport);
}
}
Answer by TSRajesh · Dec 16, 2014 at 03:08 AM
AFAIK, you have two options..
Don't "Destroy". Just Disable.
Instantiate from a Prefab (I believe this is what you do.. what's teh problem with it?)
Edit: I see some issues with your code Vs what you wrote in the description.. You said you destroy enemy at random time? But in your code, I see that you destroy immediately (in next frame), but instantiate after a random time once it collides with something.. ? That would mean the life span of the object will just be one frame. Always. (And I guess it is not the collider of the same object that you destroy.. otherwise you won't be getting any more collisions..).
Edit again: sorry, i missed that your destroy's second parameter is not a "transport", but actually a random number.. misguided by the variable name).
Its okay and I figured it out I just use the Invoke method in SpawnEnemy. But I am running into a problem where as to the enemy contiously spawns. I only want to spawn one enemy, and the once that enemy destroys itself it respawns again.
Your answer
![](https://koobas.hobune.stream/wayback/20220613174133im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
Trigger...Spawn...Destroy 1 Answer
Respawn question unanswered 0 Answers
Can't set timer 1 Answer
How to make something happen over time? 1 Answer
How to spawn a 'boss' after all enemies defeated and then kill that 'boss'? 1 Answer