My code complies and runs however It is not working as intended. The desired outcome is for a "testTile " to be placed for every Vector3 in gridPosition. This is the result of the current code.
As you can see gridPositions contains 6 different Vector3’s and 6 tiles where instantiated. There is no tile at (2,1,0) and instead an extra tile at one of the other positions. I suspect that the problem lies in the for loop but I’m out of ideas for what to try.
I have tried to add +1 or -1 to various parts of the for loop but I get an extra undesired tile and an “ArgumentOutOfRangeException” message. I thought it would be solved by adding a nullable to the end of the list but that can’t be done (so far as I know). Just what is going on here, and is there a way to right this where I get all 6 tiles to match up with the correct vector3?
public class TestLevelManager : MonoBehaviour
{
public class Grid
{
public int sizeX;
public int sizeY;
public List<Vector3> gridLocations;
public Grid(int x, int y, List<Vector3> list)
{
sizeX = x;
sizeY = y;
gridLocations = list;
}
public void CreateGrid()
{
for (int x = 0; x < sizeX; x++)
{
for (int y = 0; y < sizeY; y++)
{
Vector3 _position = new Vector3(x, y, 0f);
gridLocations.Add(_position);
}
}
}
}
void SpawnTiles()
{
for (int i = 0; i < gridLocations.Count; i++)
{
Instantiate(testTile[0]);
testTile[0].transform.position = (Vector3)gridLocations[(i)];
}
}
private int rows, colums;
public List<Vector3> gridLocations;
public GameObject[] testTile;
void Awake()
{
List<Vector3> gridLocations = new List<Vector3>();
}
void Start()
{
rows = Random.Range(1, 4);
colums = Random.Range(1, 4);
Grid cellGrid = new Grid(rows, colums, gridLocations);
cellGrid.CreateGrid();
SpawnTiles();
}
}