How can i stop Infinite Obstacles for a moment ?

Hi guys i need your help;

public GameObject obstacle;

    public GameObject player;
    
    public static float maxTime;

    public float decrease;
    public float increment;

    public float timer;
    public float timer2;

    public float range;
    // Start is called before the first frame update
    void Start()
    {
        
        maxTime = 0.6f;
        timer = 0;
        timer2 = 0;
    }

    // Update is called once per frame
    void Update()
    {
        float playerPos = player.transform.position.x;
        //Debug.Log(playerPos);
        if(timer2 > decrease)
        {
            if(maxTime > 0.25)
            {
                maxTime -= increment;
            }
        }

        if(timer>maxTime)
        {
            GameObject newObstacle = Instantiate(obstacle);

            newObstacle.transform.position = new Vector3(0,Random.Range(-10,10),0);

            newObstacle.transform.position += new Vector3(playerPos+200,0,0);
            timer = 0;
        }

        timer2 += Time.deltaTime;
        timer += Time.deltaTime;
    }

how can i stop creating for a moment, example stop for 10 seconds in every 20 seconds.

It would be amazing if you can help me guys i did some research about it but couldn’t make it on my own.

Thank you!!

i did it with if statements again, but if you have any better solutions it would be amazing so i can improve my coding skills. thank you guys

OK - I’ve taken the challenge! If you want to get better at coding, you need to know about Coroutines. A Coroutine is a section of code that can be interrupted. Normally, a function runs all the way through and cannot be interrupted. A Coroutine can halt (it’s called yielding) and wait for some condition to complete. When it restarts, it carries on from where it left off, with all its variables set as they were before yielding. A common use of Coroutines is to create a timer - the coroutine waits for a given period then continues afterwards.

The code below sets a Boolean “canMove” for a period then turns it off for a period. Those periods are serialised so you can change them in the Inspector. In practice, I wouldn’t use exactly this code but I’ve simplified it so that you get the best chance of understanding it. You only move if canMove is true.

using System.Collections;
using UnityEngine;

public class CoroTimer : MonoBehaviour
{
    [SerializeField] float moveFor = 20;
    [SerializeField] float stopFor = 10;

	bool canMove = true;

	void Start()
    {
        StartCoroutine(AllowMovement());
    }

    void Update()
    {
        if (canMove)
        {
            //Put your move code here
        }
    }

    IEnumerator AllowMovement()
    {
        while (true)
        {
			yield return new WaitForSeconds(moveFor);
			canMove = false;
			yield return new WaitForSeconds(stopFor);
			canMove = true;
		}
	}
}