public float maxSpawnDelay = 3f; //Max delay until next spawn in seconds
public float minSpawnDelay = 1f; //Min delay until next spawn in seconds
private bool _spawning; //Determine if spawn sequence is active
private float _lastSpawn; //Last time a prefab spawned
private float _curDelay; //Current delay in seconds until a spawn should occur
private int _curIndex; //Amount of objects spawned
void Start(){
_curDelay = Random.Range( minSpawnDelay, maxSpawnDelay ); //Get a new delay for next spawn
_lastSpawn = Time.time; //Cache time when begun
_spawning = true; //Starts the spawn sequence
}
//Progress the spawn sequence, should be called every time the prefab is instantiated
void OnSpawned() {
_curIndex++;
_lastSpawn = Time.time;
_curDelay = Random.Range( minSpawnDelay, maxSpawnDelay );
}
void Update() {
if( !_spawning ) {
return; //Stop if spawn sequence is not active
}
if( Time.time - _lastSpawn >= _curDelay ) { //When enough time has passed spawn a new prefab instance
Vector3 pos = RandomCircle( transform.position, 20f );
Quaternion rot = Quaternion.FromToRotation( Vector3.forward, center - pos);
Instantiate( prefab, pos, rot );
OnSpawned();
}
if( _curIndex >= numObjects ) {
_spawning = false; //Stop spawn sequence when the target number of objects has been instantiated
}
}