Looping Difficulties,Loop creates more cubes than I need

Hello Everyone, I am a programming student and I’m just starting out. The script I made needs to make a grid of cubes in a 4x4 plane and spawns them in on a void start. After my script makes the 4x4 grid of cubes it keeps going and spawns even more cubes in the same spaces as the others. Ive been troubleshooting this for about an hour thanks in advance for the help!

Heres my script:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class BattleshipScript : MonoBehaviour
{

public GameObject DummyShip;

// Start is called before the first frame update
void Start()
{
    

    GenerateCube (4, 4);

}

// Update is called once per frame
void Update()
{
    
}

public void GenerateCube (int x, int z)
{
    int xCounter = 0;
    int zCounter = 0;

    while(xCounter <x)
    {
        while(zCounter < z)
        {
            GenerateCube(xCounter, zCounter);
            zCounter++;
        }
        zCounter = 0;
        xCounter++;
    }

    Vector3 cubePosition = new Vector3(x, 0, z);

    Instantiate(DummyShip, cubePosition, Quaternion.identity); 
}

}
,Hi, Im a student for programming and I’m just starting and the script I’m using needs to be able to make a 4x4 grid of cubes when the script makes the 4x4 grid it keeps going and duplicates the grid of cubes in the same position about 3 more times. How do I get my loop to end and stop making more duplicates after the first grid of cubes is made?

Heres the script:

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

public class BattleshipScript : MonoBehaviour
{

public GameObject DummyShip;

// Start is called before the first frame update
void Start()
{
    

    GenerateCube (4, 4);

}

// Update is called once per frame
void Update()
{
    
}

public void GenerateCube (int x, int z)
{
    int xCounter = 0;
    int zCounter = 0;

    while(xCounter <x)
    {
        while(zCounter < z)
        {
            GenerateCube(xCounter, zCounter);
            zCounter++;
        }
        zCounter = 0;
        xCounter++;
    }

    Vector3 cubePosition = new Vector3(x, 0, z);

    Instantiate(DummyShip, cubePosition, Quaternion.identity); 
}

}

Thanks for the help in advance!

Hi, @ ghostfacekills478.

Congratulations on taking up coding It can be fun and rewarding. In the code you are using recursion, which makes this problem ever more complicated than it needs to be. It would be much simpler to replace the recursion call

GenerateCube(xCounter, zCounter); 

with

  Vector3 cubePosition = new Vector3(xCounter, 0, zCounter);
  Instantiate(DummyShip, cubePosition, Quaternion.identity);

Also with looping, a for loop is generally easier to use than a while loop. Your loops, without included code would be

for (int xCounter = 0; xCounter++; xCounter < x) {
    for (int zCounter = 0; zCounter++; zCounter < z) {
        // your code goes here
    }
}

I hope this help.

Steve