I’ve been looking at Tutorials and previous forums post but I still can’t wrap my head around how to find the adjacent slots in a matrix. I know the adjacent slots can be found by adding/subtracting 1 to index locations respectively but I can’t put it together in code. I thought I was getting to something but I ran into the problem of checking for indices that are out of range of the matrix, pushing back an error.
The code below:
- Spawns Blocks in a grid pattern
- adds GridObject to each index in matrix (which is a struct holding the GameObject & index location)
- [Incomplete] Checking if adjacent indices are valid
I dont know how much information would be needed to further assist, but if you need more information, feel free to ask. Thank you!
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GridSpawner : MonoBehaviour
{
public GridObject[,] matrixTable;
public int tilesPerRow = 3;
public int tilesPerColumn = 5;
float xOffset = 0;
float yOffset = 0;
float distanceBetweenTiles = 1.25f;
public GameObject blockPrefab;
void Start()
{
matrixTable = new GridObject[tilesPerRow, tilesPerColumn];
for (int tilesCreated = 0; tilesCreated < matrixTable.Length; tilesCreated++)
{
xOffset += distanceBetweenTiles;
if (tilesCreated % tilesPerRow == 0)
{
yOffset += -distanceBetweenTiles;
xOffset = 0;
}
GameObject newBlock = Instantiate(blockPrefab, new Vector2(transform.position.x + xOffset, transform.position.y + yOffset), transform.rotation);
newBlock.name = SetObjectName(newBlock, tilesCreated); //Block x
GridObject cellIndex = matrixTable[tilesCreated % tilesPerRow, tilesCreated % tilesPerColumn];
cellIndex.colorBlock = newBlock;
cellIndex.Location = new Vector2(tilesCreated % tilesPerRow, tilesCreated % tilesPerColumn);
if (tilesCreated == (tilesPerRow * tilesPerColumn - 1))
{
Vector2 cell = new Vector2();
for (int index = 0; index < matrixTable.Length; index++)
{
cell.x = matrixTable[index % tilesPerRow, index % tilesPerColumn].Location.x;
cell.y = matrixTable[index % tilesPerRow, index % tilesPerColumn].Location.y;
for (int x = (int)cell.x -1; x < cell.x + 2; x += 2)
{
if (!matrixTable[1,1].Equals(null))
{
Debug.Log(matrixTable[(int)cell.x, (int)cell.y].GetName());
}
}
}
}
}
}
string SetObjectName (GameObject obj, int index)
{
return (obj.name + " " + index);
}
}
[System.Serializable]
public struct GridObject
{
public GameObject colorBlock;
public Vector2 Location;
public string GetName()
{
return colorBlock.name;
}
}