Home > Mobile >  How do I create a time interval for every 15 sec of the game time spawn pizza
How do I create a time interval for every 15 sec of the game time spawn pizza

Time:07-29

How do I create a time interval for pizza spawning? During the game time for every 15s start spawning pizza for 5 seconds and stop, then start spawning pizza again after 15s

   IEnumerator SpawnPizzaCoroutine()
    {
        while (true)
        {
            int spawnPointX = Random.Range(-18, -5);
            int spawnPointY = Random.Range(5, 0);
            Vector3 spawnPosition = new Vector3(spawnPointX, spawnPointY, 0);
            Instantiate(Pizza, spawnPosition, Quaternion.identity);
            yield return new WaitForSeconds(3f);
        }
    }
void Start()
    {
        StartCoroutine(SpawnPizzaCoroutine());
    }

CodePudding user response:

You can use the InvokeRepeating for that purpose. Have a look here: https://docs.unity3d.com/ScriptReference/MonoBehaviour.InvokeRepeating.html

You could execute the function every 20 seconds then your coroutine for 5 seconds. The result would be, that you spawn pizzas for 5 seconds and after 15 seconds another 5 seconds of pizza spawning would begin.

    void Start()
    {
        InvokeRepeating("SpawnPizza", 15f, 20f);
    }   
    void SpawnPizza()
    {            
        StartCoroutine(SpawnPizzaCoroutine());
    }
  
    IEnumerator SpawnPizzaCoroutine()
     {
        //Do your thing for 5 seconds
     }

CodePudding user response:

You just need to keep track of the elapsed time between pizzas in a float type variable

private bool spawningPizza;
private float nextSpawnTime;

private void Start()
{
    StartCoroutine(SpawnPizzaCoroutine());
}

private IEnumerator SpawnPizzaCoroutine()
{
    while (true)
    {
        nextSpawnTime  = Time.deltaTime;

        if (nextSpawnTime >= 15)
        {
            spawningPizza = true;

            int spawnPointX = Random.Range(-18, -5);
            int spawnPointY = Random.Range(5, 0);
            Vector3 spawnPosition = new Vector3(spawnPointX, spawnPointY, 0);
            Instantiate(Pizza, spawnPosition, Quaternion.identity);

            yield return new WaitForSeconds(5f);

            nextSpawnTime = 0;
            spawningPizza = false;
        }
    }
}
  • Related