I am making a game where objects spawn at random locations and you need to shoot them, but I also want to make the objects spawn at random intervals of time, and I do not know how to do that.
This is the code that I am using:
` public GameObject enemyPrefabs;
private int SpawnRangeZ = 47;
private float startDelay = 0.01f;
public float spawnInterval = 1.5f;
void Start()
{
InvokeRepeating("SpawnRandomEnemy", startDelay, spawnInterval);
}
void Update()
{
}
void SpawnRandomEnemy()
{
int enemyIndex = Random.Range(0, enemyPrefabs.Length);
Vector3 spawnPos = new Vector3(65, 0, Random.Range(-SpawnRangeZ, SpawnRangeZ));
Instantiate(enemyPrefabs[enemyIndex], spawnPos, enemyPrefabs[enemyIndex].transform.rotation);
}`
Hi!
You can’t do this directly with the InvokeRepeating function, but you can kind of fake it by calling Invoke in the SpawnRandomEnemy function on itself:
void Start()
{
Invoke("SpawnRandomEnemy", startDelay);
}
void SpawnRandomEnemy()
{
//[Spawn Enemy]
Invoke("SpawnRandomEnemy", spawnInterval + Random.Range(-0.5f, 0.5f));
}
You can then use whatever formula you want to get a desired random interval.
Hope this helps!