I have this "Game" class that gets instantiated at Start and sets up the field for Minesweeper and in this process I count the adjacent Mines for each field.
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Game
{
public int Width;
public int Height;
public int NumOfMines;
public Field[,] Board;
public Game(int width = 8, int height = 8, int numOfMines = 10)
{
this.Width = width;
this.Height = height;
this.NumOfMines = numOfMines;
Board = new Field[height, width];
InitializeBoard();
}
public void InitializeBoard()
{
for (int row = 0; row < Height; row++)
{
for (int column = 0; column < Width; column++)
{
Board[row, column] = new Field();
}
}
// Board.Initialize();
// foreach (var field in Board)
// {
// field.IsMine = false;
// }
var rnd = new System.Random();
for (int i = 0; i < NumOfMines; i++)
{
int mineRow = 0;
int mineColumn = 0;
do
{
mineRow = rnd.Next(Height);
mineColumn = rnd.Next(Width);
} while (Board[mineRow, mineColumn].IsMine);
Board[mineRow, mineColumn].IsMine = true;
Board[mineRow, mineColumn].NumOfAdjacentMines = null;
}
for (int row = 0; row < Height; row++)
{
for (int column = 0; column < Width; column++)
{
if (!Board[column, row].IsMine)
Board[row, column].NumOfAdjacentMines = CountAdjacentMines(new Vector2Int(column, row));
}
}
}
private int CountAdjacentMines(Vector2Int pos)
{
Debug.Log(pos);
int counter = 0;
for (int y = pos.y - 1; y <= pos.y + 1; y++)
{
for (int x = pos.x - 1; y <= pos.x + 1; x++)
{
try
{
Debug.Log($"Checking {x + ":" + y} for a mine");
if (Board[x, y].IsMine)
{
counter++;
}
}
catch (Exception ex)
{
Debug.LogError(ex + ", Pos: " + x + ":" + y);
continue;
}
}
}
return counter;
}
}
Why does Unity freeze without any notes? If I throw the exception, unity reacts normally. (I have to write this so StackOverflow let's me post this...)