I have two objects: Tile and TileGrid which have their own scripts. TileGrid can generate a 2d array of Tiles. Then I am trying to attach every Tile around the Tile in the script for every Tile, so all of my Tiles will have a reference to their 'neighbors'. I use a dictionary. To do that I wrote a function which is accessing TileGrid's 2d array of Tiles. Unfortunately, a NullReferenceException is thrown.
TileGridScript.cs
public class TileGridScript : MonoBehaviour
{
public GameObject[][] tileGrid;
// Other properties ...
public void MakeGrid(int width = 64, int height = 64)
{
tileGrid = new GameObject[width][];
for (int x = 0; x < width; x++)
{
tileGrid[x] = new GameObject[height];
for (int y = 0; y < height; y++)
{
// !!! Instantiating tiles !!!
tileGrid[x][y] = Instantiate(grassPrefab, new Vector2(x - width / 2, y - height / 2), Quaternion.identity);
}
}
// !!! Call the function to connect Tiles !!!
for (int x = 0; x < width; x++)
for (int y = 0; y < height; y++)
tileGrid[x][y].GetComponent<TileScript>().AttchTile(this);
}
}
TileScript.cs
public class TileScript : MonoBehaviour
{
public Dictionary<string, GameObject> connectedTiles;
// Other properties ...
private void Start()
{
connectedTiles = new Dictionary<string, GameObject>(8);
}
public void AttchTile (TileGridScript tileGridScript)
{
for (int biasx = -1; biasx < 2; biasx++)
{
for (int biasy = -1; biasy < 2; biasy++)
{
switch (biasx)
{
case -1: // L
switch (biasy)
{
case -1: // D
try
{
// !!! Catches the error here !!!
connectedTiles["DL"] = tileGridScript.tileGrid[(int)position.x + biasx][(int)position.y + biasy];
}
catch (System.IndexOutOfRangeException) { }
break;
}
// etc for every Tile. P.S. DL means Down and Left.
// in this way I add all 8 Tiles around that
}
}
}
}
}
GameManager.cs
public class GameManager : MonoBehaviour
{
public GameObject tileGridPrefab;
// Other properties...
void Start()
{
// !!! Here I generate the Tile Grid !!!
tileGridPrefab.GetComponent<TileGridScript>().MakeGrid(24, 16);
}
}
I tried to write this function in TileGrid's script and call it from that. If I don't initialize a dictionary in Start() it does okay. Then when I access it from another script, it falls with the same error. I tried to change the order of these scripts in the editor.
What is the reason for the problem and how can I fix it?
The problem is that Start()
is calling after AttachTile()
.
I should use Awake()
instead. I get TileGrid object in Awake()
and then can use it in AttachTile()
function.