Home > Software design >  How do I set up a time loop in Unity
How do I set up a time loop in Unity

Time:06-27

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

public class Spawner : MonoBehaviour

{

    public GameObject enemy;
    float defaultSpawnTime = 1f;
    float spawnTime = 1f;
    float realTime = 4f;

void Start()
{
    
}


void Update()
{
    spawnTime-= Time.deltaTime;
    realTime  = Time.deltaTime;
    if (spawnTime < 0 && realTime<30f && realTime>5f)
    {
        
        GameObject go = Instantiate(enemy, new Vector3(Random.Range(-2.3f, 2.3f), 8f, 0), Quaternion.Euler(0, 0, 0)) as GameObject;
        GameObject go1 = Instantiate(enemy, new Vector3(Random.Range(-2.3f, 2.3f), 8f, 0), Quaternion.Euler(0, 0, 0)) as GameObject;
  
        spawnTime = defaultSpawnTime;
        if (realTime > 30f)
        {
            realTime = 0f;
        }

    }
   
}

}

**My game is 2D. In the game, a meteorite rains every 2 seconds from above. The player struggles with these.

But since the game is very tiring, I do not want meteorites to rain for 5 seconds every 30 seconds, so the player will have the opportunity to rest.

I also wanted to create a time variable and increase it in real time. And I tried the meteor shower to happen, provided the time was between 5 and 30.

If the time is greater than 30, I wanted to return it to 0 and loop it, but after 30 it continues to progress. I don't know where I went wrong, can you help me?**

CodePudding user response:

It gets hard to manage time like that after you add few timers. Try using Coroutines like:

void Start(){
    StartMeteorShower(5f);
}

void StartMeteorShower(float time){
    StartCoroutine(StartMeteorShowerDelayed(time);
}

IEnumerator StartMeteorShowerDelayed(float delay){
    yield return new WaitForSeconds(delay);
    StartCoroutine(MeteorShowerCoroutine());
}

IEnumerator MeteorShowerCoroutine(){
    var startTime = Time.time;
    var delay = new WaitForSeconds(1f);

    do
    {
        SpawnMeteor();
        yield return delay;
    }
    while(Time.time - startTime < _meteorShowerDuration);

    //here you can queue next meteor shower
    StartMeteorShower(30f);
}

CodePudding user response:

Just move the if statment outside of first if. Because after realtime > 30 you condition " && realTime<30f && " not fulfilled

void Update()
{
    spawnTime-= Time.deltaTime;
    realTime  = Time.deltaTime;
    
    if (spawnTime < 0 && realTime<30f && realTime>5f)
    {
        GameObject go = Instantiate(enemy, new Vector3(Random.Range(-2.3f, 2.3f), 8f, 0), Quaternion.Euler(0, 0, 0)) as GameObject;
        GameObject go1 = Instantiate(enemy, new Vector3(Random.Range(-2.3f, 2.3f), 8f, 0), Quaternion.Euler(0, 0, 0)) as GameObject;

        spawnTime = defaultSpawnTime;
    }

    if (realTime > 30f)
    {
        realTime = 0f;
    }
}
  • Related