How to instantiate prefabs at random times within a time constraint?

I want to instantiate these meteors at random times so the game doesn’t become predictable. Also maybe add in the code for random spacial position? It’s like one of those infinite runner games.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class SpawnMeteor : MonoBehaviour
{

public Transform center;
public Transform left;
public Transform right;
private float cenTime = 3f;
private float rigTime = 4f;
private float lefTime = 6f;
public GameObject meteor;
private float centerCoin = 1f;
private float rightCoin = 2f;
private float leftCoin = 3f;
public GameObject coins;

// Start is called before the first frame update
void Start()
{
    Instantiate(meteor, center.position, center.rotation);
}

// Update is called once per frame
void Update()
{
    cenTime -= Time.deltaTime;
    rigTime -= Time.deltaTime;
    lefTime -= Time.deltaTime;
    centerCoin -= Time.deltaTime;
    rightCoin -= Time.deltaTime;
    leftCoin -= Time.deltaTime;

    if (cenTime < 0)
    {
        cenTime = 3f;
        Instantiate(meteor, center.position, center.rotation);
    }

    if(rigTime < 0)
    {
        rigTime = 4f;
        Instantiate(meteor, right.position, right.rotation);
    }

    if(lefTime < 0)
    {
        lefTime = 6f;
        Instantiate(meteor, left.position, left.rotation);
    }

    if (centerCoin < 0)
    {
        centerCoin = 1f;
        Instantiate(coins, center.position, center.rotation);
    }

    if(rightCoin < 0)
    {
        rightCoin = 2f;
        Instantiate(coins, right.position, right.rotation);
    }

    if(leftCoin < 0)
    {
        leftCoin = 3f;
        Instantiate(coins, left.position, left.rotation);
    }
}

}

For instantiating at random times, make a public float randomtime, ‘public float mintime’ and public float maxtime, and then use randomtime = Random.Range(mintime, maxtime);

Then you can just plug in randomtime whenever you are instantiating a meteor. And use randomtime = Random.Range(mintime, maxtime). before each time you instantiate, it will override the variable with a new random value.

I think I have a solution, not tested, might (probably) will have spelling errors, so use at own risk :slight_smile:

Make a float called timeTillMeteor, float called currentTime, and a float called maxTime.

At Start() do this:

timeTillMeteor = Random.Range(0, maxTime);

Then in Update(), I would do something like this:

currentTime += Time.deltaTime;
if(currentTime > timeTillMeteor)
{
InstantiateMeteor();
}

Then Create a new function for the instantation:

public void InstantiateMeteor()
{
Instantiate(meteor, whateverPositionYouWant, whateverRotationYouWant);
timeTillMeteor = Random.Range(0, maxTime);
currentTime = 0;
}

I don’t know what all those other if statements mean, but if you need them, then you can add them in the InstantiateMeteor() method rather than have them in the Update like that.

Hope that helps.