- Home /
Duplicate Question
Finding Coordinates of Objects in a List
I made a list of Tiles that are instantiated. I want to retrieve a location of objects later in a new function. I tried using transform.position and GetComponent().transform.position but I keep getting NullReferenceException: Object reference not set to an instance of an object. This line is where the error occurs: Debug.Log ("Tiles: " + tiles[i].GetComponent().transform.position);
public List<Tile> tiles = new List<Tile>();
public int gridWidth;
public int gridHeight;
public GameObject tilePrefab;
// Use this for initialization
void Start () {
for (int y = 0; y < gridHeight; y++) {
for (int x = 0; x < gridWidth; x++)
{
GameObject g = Instantiate(tilePrefab, new Vector3(x,y,1), Quaternion.identity) as GameObject;
g.transform.parent = gameObject.transform;
tiles.Add(g.GetComponent<Tile>());
}
}
gameObject.transform.position = new Vector3 (-3.5f, -3.5f, 1);
}
public void CheckTiles(){
for (int i = 0; i < tiles.Count; i++) {
Debug.Log ("Tiles Count: " +tiles.Count);
Debug.Log ("Tiles: " + tiles[i].GetComponent<Tile>().transform.position);
Debug.Log("tiles : " + tiles[i].transform.position);
}
}
Please always post full errors and the exact line on which it happens. Presumably g.GetComponent< Tile >()
is null. So presumably tilePrefab
doesn't have a Tile
script. Unless g
in g.GetComponent< Tile >()
is null, which means tilePrefab
is null.
This line is where the error occurs: Debug.Log ("Tiles: " + tiles[i].GetComponent().transform.position);
Since the list contains instances of the Tile class, it seems like trying to access the component Tile of the currently iterated tile won't work. It would work were the list composed of gameObjects, though. If you want to get the transform.position of the gameobject whose Tile component is included in the list, try something like
Debug.Log("tiles : " + tiles[i].gameObject.transform.position);
which should work, but the way you did it in the second Debug line should be fine as well. So in short, the line tiles[i].GetComponent().transform.position makes no sense and rightly gives an error, so just delete it and use the second one or the one I posted above for the transform.position.
I tried using tiles[i].gameObject.transform.position) but the error is the same. NullReferenceException: Object reference not set to an instance of an object.