I want to make a proximity spawner over time but it doesn't work

I’m tryin to make a spawner over time but it doesn’t wanna work. The enemies keep spawning infinitely, I tried everything.

It looks like the coroutine is not working for some reason?

This is my code anyway:

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

public class TombSpawner : MonoBehaviour
{
    public GameObject mobPrefab;

    public Transform mobSpawner;

    public Transform playerDistance;
    private float spawnerRadius = 3f;


    public bool canSpawn = true;
    private void Awake()
    {
        if (playerDistance == null) playerDistance = FindObjectOfType<PlayerLife>().transform;
    }


    void Update()
    {
        if (playerDistance == null) return;
        float distance = Vector2.Distance(playerDistance.position, transform.position);

        if (distance < spawnerRadius)
        {
            StartCoroutine(CanSpawnAgain());
        }
        if(canSpawn)
        {
            Instantiate(mobPrefab, mobSpawner.position, mobSpawner.rotation);
        }
    }


    IEnumerator CanSpawnAgain()
    {
        canSpawn = false;
        yield return new WaitForSeconds(10f);
        canSpawn = true;
    }

}

I think there are two main issues. First, you are starting the coroutine every frame while the condition is met. This is going to cause a large number of the same coroutine to run.

Second, the coroutine has no loop and leaves leaves canSpawn set to true after it runs. This means canSpawn will be true after 10s and it will just stay true.

Since this script is running every Update anyway, it may be easier to use a timer in the Update() method.

private float spawnPeriod = 10f;
private float spawnTimer = 0f;

void Update()
{
    if (playerDistance == null) return;
    float distance = Vector2.Distance(playerDistance.position, transform.position);

    if (distance < spawnerRadius)
    {
        spawnTimer += Time.deltaTime;
        if(spawnTimer >= spawnDuration)
       {
            spawnTimer -= spawnDuration;
            Instantiate(mobPrefab, mobSpawner.position, mobSpawner.rotation);
       }
    }
    else
    {
        //Depending on your desired behavior, you could st spawnTimer = 0 here.
    }
    
}