Dungeon Generator problems

I am trying to make a Dungeon following a perlin noise cluster, but only in 1 cluster, not the whole room. so I made a self duplicating stucture that should delete themselfs after spreading, and should die out after expanding to the size of a cluster.

But for some reason, I get an infinite loop. It doubles back on itsef, and does not get deleted once it does that.

Here is my script:

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

public class RoomGen : MonoBehaviour
{
    public float RoomValue;
    public float seed = 1.457582f;
    public GameObject Marker;
    public GameObject Self;
    // Start is called before the first frame update
    void Start()
    {
    }
    void LateUpdate()
    {
        RoomValue = Mathf.PerlinNoise(transform.position.x * seed, transform.position.z * seed);
        if (RoomValue >= .4f)
        {
            Instantiate(Marker, transform.position, transform.rotation);
            Instantiate(Self, transform.position + new Vector3(-1, 0 ,0), transform.rotation);
            Instantiate(Self, transform.position + new Vector3(1, 0, 0), transform.rotation);
            Instantiate(Self, transform.position + new Vector3(0, 0, -1), transform.rotation);
            Instantiate(Self, transform.position + new Vector3(0, 0, 1), transform.rotation);
            Destroy(this.gameObject);
        }
        else
        {
            Destroy(this.gameObject);
        }
    }
    
    
    private void OnCollisionStay(Collision collision)
    {
        Destroy(this.gameObject);
    }
    
}

First off, looking at your seed value and your positions used, it’s worth noting that Unity’s Perlin noise function repeats with every value of 1.0. In a worst-case scenario for what you’re doing (a seed value of 1), you would have the same value from the noise function in every case.

However, your problem lies in the fact that you’re creating objects on all four sides with no safety in place. If any two adjacent spaces both result in a noise value of 0.4 or higher, they will recreate each other endlessly.

Possible (not necessarily robust) solutions include modifying the seed any time the new objects are generated, or keeping track of a simple list of “used locations” to prevent remaking an object at a location that’s been used previously.