- Home /
The question is answered, right answer was accepted
How to spawn a new prefab when the last one was destroyed??
UNITY 2D C#
I have a script. When my player is alive, the enemy manager counts down the time and then creates an opponent.
I would like the EnemyManager to respawn a new opponent, but only when the last one is destroyed. So, if the created opponent (being a prefab) dies, EnemyManager should start counting the time again and if a certain number of time passes, he should generate another opponent.
Any help?
My script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SpawnManagerWithTime : MonoBehaviour
{
public GameObject[] prefab;
public PlayerBehaviour behaviourscript;
public float minTime;
public float maxTime;
float time = 0f;
private float spawnTime;
private int randomPrefabs;
void Start ()
{
spawnTime = Random.Range(minTime, maxTime);
randomPrefabs = Random.Range (0,2);
}
void Update()
{
time += Time.deltaTime;
//Check if its the right time to spawn the object
if(!behaviourscript.dead & time >= spawnTime ){
Instantiate(prefab[randomPrefabs], transform.position, Quaternion.identity);
time = 0f;
}
}
}
Answer by polan31 · Feb 24, 2020 at 09:39 PM
There was no subject. Good advice for everyone, a better option is to disable and enable the SpawnManager object from the Player object :)
Answer by logicandchaos · Feb 23, 2020 at 10:48 PM
Instead of checking if it is dead, you should do it when it dies, instead of setting a dead variable you can Invoke() the function in x milliseconds.
Invoke("SpawnEnemy",spawnTime);
and is you disable and move the enemy then Enable it, it is more performant.