Having trouble randomly placing objects with no collisions

i’m trying to get a script to work that clones and places X amount of cubes from a prefab. Originally i had it set up to place a cube in a random position and if it detects a collision it runs the randomization again until all cubes are randomly placed. I’m trying to improve this by having the script text if there’s a collision in the random position and place the cube there if it doesn’t find a collision. That way when i run the game there isn’t that brief moment where all the cubs are jumping around trying to find a random position with no collisions. My Problem is my Current script i have just causes unity to not respond and then i have to restart unity.

I’m pretty sure iv’e either created and infinite while loop or i have a hunch it may have something to do with either how iv’e cloned or am running my collision test because when i ran the collision test as an if statement and set the cubes to a diferant color before placing it if it found a collision all my cubes were placed with a different color regardless of if there was a collision. here’s my script any help or advice would be really appreciated

public class randomtest : MonoBehaviour {

    public float minX;
    public float maxX;
    public float minZ;
    public float maxZ;

    void Start()
    {
        randomize();
    }

    void randomize()
    {
        var newpos = new Vector3(Random.Range(minX, maxX), 1, Random.Range(minZ, maxZ));
        var checkResult = Physics.OverlapSphere(newpos, 1);

        while (checkResult.Length != 0)
        {
            //  Renderer rend = GetComponent<Renderer>();
            //  rend.material.shader = Shader.Find("Specular");
            //  rend.material.SetColor("_SpecColor", Color.green);
            newpos = new Vector3(Random.Range(minX, maxX), 1, Random.Range(minZ, maxZ));
            checkResult = Physics.OverlapSphere(newpos, 1);
        }
        gameObject.transform.position = newpos;
    }
}

The infinite loop may indicate that there is no room for another cube to fit in without intersecting other cubes.
And it would be very inefficient to spot the position by randomly placing the cube hoping it fits.

I’d do that ‘pseudo-random’. That is, I’d incrementally placing one right next to previous cubes with a little randomness, and if there aren’t enough room(say, the checkResult.Length != 0 for more than 10 loops or so) i’d break the while loop.

i’ll give that a try but based on my tests the program would not respond weather i tried spawning 2 cubes or 10 cubes which makes me think i might be testing the collisions wrong and thus its never able to escape the while loop. but i’m still very new to unity so there could be something else i’m missing.

Edit: so adding a loop counter gets me out of the crashing but it still leaves me with the issue of having my cubes occasionally overlapping each other when i spawn them