Creating Simple 8x8 gameBoard..my logic is flawed and need help

ok so I think I am close but would appreciate feedback to see where I might be going wrong.

My goal is to dynamically create a simple 8x8 gameboard and then populate either a List or Array(not sure which is better) so I can access specific squares or tiles in the game board later in my class.

First I define a Tiles array

 public GameObject[,] Tiles { get; set; }

Then also a tile instance for accessing specific tles in the finished board.

        private GameObject _tileInstance;

Then in my Start method I create a new Tiles 2D array populated with placeholders

 Tiles = new GameObject[8, 8];

I then instantiate physical tilePrefab objects to create the entire game board

            for (int i = 1; i <= 8; i++)
            {
                for (int j = 1; j <= 8; j++)
                {
                    int xVal;
                    int zVal;
                    xVal = initX + ((j - 1) * 2);
                    zVal = initZ - ((i - 1) * 2);
                    _tileInstance = Instantiate(tilePrefab, new Vector3(xVal, 0, zVal), Quaternion.Euler(0, 0, 0)) as GameObject;

And also use AddComponent to add a GridTile class to each tile

                    _tileInstance.AddComponent<GridTile>();

And then lastly (and most importantly) I associate each index in the Tiles array with these instances

Tiles[i-1, j-1] = _tileInstance;

Is my logic above correct? Would you change anything?

I’m having huge problems when it comes to accessing specific tiles in my Tiles array.

That’s pretty much what I would do. I’m doing something like that for a dungeon right now, but the floor is one big plane, I just position the walls using integer values, and move the player the same way. I don’t use an array.

Would probably make a const member for the board size rather than having the magic number 8 all over the place

I’d change the for loops to be zero based and use i in the inner loop (convention, to make the tightest loop on the x parameter)

            for (int j = 0; i < boardSize; j++)
            {
                for (int i = 0; i < boardSize; i++)
                {
                    var pos = initialOffset + new Vector3(i*spacing, 0, j*spacing);
                    var _tileInstance = Instantiate(tilePrefab, pos, Quaternion.Euler(0, 0, 0)) as GameObject;

And make sure that this is in the loops (just concerned by the lack of indenting on it, but outside the loop it’s ofcouse only setting a value outside the array where i and j exceed there max values)

                    Tiles[i, j] = _tileInstance;

Hard to know how helpful this is without a clue as to your present issues.

Thanks! Great optimization suggestions. Got everything working.