Unity Crash?

Hello, i was wondering if anyone could help me with this.
I’m trying to do a simple game. In this game there is a grid (x,y) with size “a”. The grid is like sudoku there cant be two repeated numbers in the same line and column

I had to functions to fill the grid: predifined 4x4 and random. When change it to random Unity crashes.

here is my random function:

function RandomMatriz(size:int)
{

var matriz = new Array(size);
for (i = 0; i < size; i++)
{
matriz[i] = new Array(size);
}

var x = 0;
var y = 0;
var y_check = 0;
var x_check = 0;
var repeat = false;

for (x = 0; x < size; x++)
{
	for (y = 0; y < size; y++)
	{
		repeat = false;
		
		matriz[x][y] = Random.Range(1,tamanho);
		
		//-------------------- Verify vertically ----------------------------
		if(y > 0)
		{
			
			for (y_check = 1; y_check <= y; y_check++)
			{
				if(matriz[x][y] == matriz[x][y-y_check])
				{
					repeat = true;
				}
			}
		}
		
		//-------------------- Verify horizontally ----------------------------
		if(x > 0)
		{
			for (x_check = 1; x_check <= x; x_check++)
			{
				if(matriz[x][y] == matriz[x-x_check][y])
				{
					repeat = true;
				}
			}
		}
		
		if (repeat == true)
		{
			y--;
		}
	}		
}

return matriz;

}

If you could help me i would appreciate

Bump

My immediate thought is that you’re likely running into an infinite loop with “repeat = true) y–.”

Instead of doing this in a loop - why not build a list of all valid numbers first and choose randomly from that valid list - instead of choosing randomly from all ints and looping if it picks an invalid number? Something like…

for (x = 0; x < size; x++)
    {
        for (y = 0; y < size; y++)
        {
            // Build a list of all VALID numbers for this slot
            List<int> validNumbers = new List<int>();
            for (int i = 1; i < tamanho; i++){
                bool iValid = true;
                // loop through your checks here, and set iValid to false if i already exists
                if (iValid){
                    validNumbers.Add(i);
                }
            }
            
            if (validNumbers.Count == 0){
                Debug.LogError("No valid number found for slot " + x + ", " + y);
                // log relevant info
                return null;
            } else {
                matriz[x][y] = validNumbers[Random.Range(0,validNumbers.Count)];
            }
        }      
    }