- Home /
Cant fetch components from GameObjects stored in an array?
I am developing a game which uses a turn based grid movement system, early on I instantiate every tile and store each of them in a 2d array:
public void GenerateMapVisuals()
{
tilesOnMap = new GameObject[mapSizeX, mapSizeY];
for (int x = 0; x < mapSizeX; x++)
{
for (int y = 0; y < mapSizeY; y++)
{
TileType tt = tileTypes[tiles[x, y]];
GameObject go = (GameObject)Instantiate (tt.tileVisualPrefab as GameObject, new Vector3 (x, y, 0), Quaternion.identity);
ClickableTile ct = go.GetComponent<ClickableTile>();
ct.TileX = x;
ct.TileY = y;
ct.map = this;
tilesOnMap[x, y] = go;
}
}
}
each tile has a script component which contains information such as its location as well as if it is occupied and the unit that is occupying it. I also utilize a pathfinding algorithm in order to determine which tiles a unit can move to, I want the algorithm to exclude tiles which are occupied, so once the algorithm completes I want it to check each node that it has determined the unit can move to, get the x, y coordinates of it, and get the tile at the x,y's script and check whether or not it is occupied However, when I attempt to do this with
foreach(Node node in FinalMovementHighlight)
{
GameObject tileinq = tilesOnMap[node.x, node.y];
if(tileinq.GetComponent<ClickableTile>().isOccupied == true)
{
FinalMovementHighlight.Remove(cool);
}
}
I get the following error at if(tileinq.GetComponent().isOccupied == true) NullReferenceException: Object reference not set to an instance of an object I hope this is clear enough if not I am happy to provide additional context.
there are 2 options,
a. the array tileOn$$anonymous$$ap is initialize but has not been filled b it has been filled but the gameobject inside tileOn$$anonymous$$ap has no clickabletile
simply add a Debug.Log() to the tileinq.name to see what object is the one getting called, or debug and stop the script in that line
Your answer
Follow this Question
Related Questions
Array Out of Index (When it Really is not??) 1 Answer
Help with editing array from inside functions for PID controller (C#)[Fixed] 1 Answer
How do I fix this problem-it won't let me start my game in Unity because of an override problem 1 Answer
Script Error 1 Answer
IndexOutOfRangeException: Array index is out of range 2 Answers