How can I set properties on multiple clones in a generic list after instantiation.

I don’t understand why this does not work:

Vector3 pos = new Vector3(x,0,y);    				
TerrainTiles.Add(Instantiate(Resources.Load("Prefabs/TerrainTile"), pos, Quaternion.identity) as TerrainTile);
Debug.Log("List items: " + TerrainTiles.Count.ToString());
TerrainTiles[TerrainTiles.Count - 1].xPosition = x;

Running the debug log shows that the list items are being created but when I try to reference any of them as in the last line of code above I am getting a NullReferenceException.

By the way, if you would kindly post your response as an answer I would be happy mark it as the answer.

1 Answer

1

Have you tried using a version of Resources.Load that uses an explicit Type?
Either:

TerrainTiles.Add(Instantiate(Resources.Load("Prefabs/TerrainTile", typeof(TerrainTile)), pos, Quaternion.identity) as TerrainTile);

or:

TerrainTiles.Add(Instantiate(Resources.Load<TerrainTile>("Prefabs/TerrainTile"), pos, Quaternion.identity) as TerrainTile);

It looks like the generic version was added at some point after Unity 4.0.0. My original test was using 4.3.1, which worked fine, but when I tried the test in 4.0.0 I got the same compile error. It would be nice if the Unity docs allowed you to change the version (like in the MSDN docs).