I have created this script to spawn my buttons randomly but do not know how to alter the times they individually spawn as they all spawn at the same time. I can't see them and have not spawned however in the Hierarchy they are being created.
Public class RandomSpawn: MonoBehaviour {
public GameObject prefab1, prefab2, prefab3, prefab4, prefab5;
public float spawnRate = 2f;
float nextSpawn = 0f;
int whatToSpawn;
// Update is called once per frame
void Update() {
if (Time.time > nextSpawn)
{
whatToSpawn = Random.Range(1, 6);
switch (whatToSpawn)
{
case 1:
Instantiate(prefab1, transform.position, Quaternion.identity);
break;
case 2:
Instantiate(prefab2, transform.position, Quaternion.identity);
break;
case 3:
Instantiate(prefab3, transform.position, Quaternion.identity);
break;
case 4:
Instantiate(prefab4, transform.position, Quaternion.identity);
break;
case 5:
Instantiate(prefab5, transform.position, Quaternion.identity);
break;
}
nextSpawn = Time.time + spawnRate;
}
What am I missing?
Use Time.deltaTime
value ,
https://docs.unity3d.com/ScriptReference/Time-deltaTime.html
private float _t = 0;
private SpawnRate = 2;
void Update() {
_t += Time.deltaTime;
if (_t > SpawnRate)
{
whatToSpawn = Random.Range(1, 6);
switch (whatToSpawn)
{
case 1:
Instantiate(prefab1, transform.position, Quaternion.identity);
break;
case 2:
Instantiate(prefab2, transform.position, Quaternion.identity);
break;
case 3:
Instantiate(prefab3, transform.position, Quaternion.identity);
break;
case 4:
Instantiate(prefab4, transform.position, Quaternion.identity);
break;
case 5:
Instantiate(prefab5, transform.position, Quaternion.identity);
break;
}
_t = 0;
}