- Home /
Array not Initialized for some reason
The array tiles in the Field class is for some reason null. Here's the script:
private void GenerateTiles(int k, int j) {
fields[k, j].tiles = new Tile[tileMapSize, tileMapSize];
Tile[,] fieldTiles = fields [k, j].tiles;
for (int x = 0; x < 10; x++) {
for (int y = 0; y < 10; y++) {
GameObject newTile = BuildTile (1f, "Tile");
newTile.name += "_" + x + y;
newTile.transform.SetParent (fields[k, j].field);
newTile.transform.localPosition = new Vector3 (x * tileSize - (float)fieldSize / 2f + (float)tileSize / 2f, 0f, y * tileSize - (float)fieldSize / 2f + (float)tileSize / 2f);
newTile.GetComponent<MeshRenderer> ().material = materials [0];
fieldTiles [x, y] = new Tile (fields[k, j], newTile.transform.position, newTile.transform);
}
}
}
public class Field {
public Transform fieldParent;
public Transform field;
public Transform emptyField;
public Tile[,] tiles;
public Vector2 fieldCoordinates;
public Field(int arraySize, Vector2 coordinates, Transform parent) {
tiles = new Tile[arraySize, arraySize];
fieldCoordinates = coordinates;
fieldParent = parent;
}
public Field(Transform obj, Vector2 coordinates, Transform parent) {
fieldParent = parent;
fieldCoordinates = coordinates;
field = obj;
}
public Tile GetTile(int x, int y) {
return tiles[x, y];
}
what line do you get the error? also show us where you create your fields array
Answer by Bunny83 · Jul 13, 2017 at 11:20 AM
Are you sure that the array is null or maybe just an element is null? You use this to initialize the array:
fields[k, j].tiles = new Tile[tileMapSize, tileMapSize];
but you use those for loops to initialize
for (int x = 0; x < 10; x++) {
for (int y = 0; y < 10; y++) {
If tileMapSize is larger than "10" you will have null elements in your array. If tileMapSize is smaller than 10 the for loop will throw an index out of bounds exception. Since you seemingly get a null reference exception i guess tileMapSize is larger than 10 and you try to access an element with index larger than "9".
I guess you want to replace that magic number "10" with "tileMapSize" in those two for loops
tile$$anonymous$$apSize is 10. When I write fields[5, 5] for example, it works, but when I pass my field to a method, the field is null. For Example : public Field[,] fields
void Start() {
Some$$anonymous$$ethod(fields[5, 5]);
}
void Some$$anonymous$$ethod(Field f) {
Tile[,] tiles = f.tiles;
Debug.Log(tiles[0, 0].name) // this returns null;
Debug.Log(fields[5, 5].tiles[0, 0].name) // this returns the tile name;
}
Without further checks i can guarantee that your posted example will yield the same result in both cases. Either there is something else missing or you interpreting the results wrong.