- Home /
NullReferenceException after instantiating.
I was hoping someone could tell me why I'm getting a NullReferenceException error with this code. I wrote something similar to this in JS and I'm trying to rework everything into C#. The error is coming from the line
mapTile.name = "Map Tile "+xLocation+", "+zLocation; I have no clue why, I could do this in JS. If I comment it out, I get the same thing with the next line. How do I properly reference something I've just instantiated?
public void BuildMap () {
//BuildMap performs a loop which will create map tiles row by row, column by column, with dimensions xBoundary and yBoundary.
for(int i = 0; i < xBoundary*zBoundary; i++){
//determines the current tiles location in the grid.
xLocation = (int)i%xBoundary;
zLocation = (int)Mathf.Floor(i/xBoundary);
//Creates the map tile at coordinates xLocation, 1, zLocation, with no rotation. This object is now GameObject mapTile.
mapTile = Instantiate (mapTilePrefab, new Vector3(xLocation, 1, zLocation), Quaternion.identity) as Transform;
//Assigns a name to the map tile for the heirarchy.
mapTile.name = "Map Tile "+xLocation+", "+zLocation;
mapTileScript = mapTile.FindChild("Map Tile Collider").GetComponent(typeof(MapTileColliderBehaviour)) as MapTileColliderBehaviour;
//Assigns the tile a room value, and its x and z values.
mapTileScript.roomValue = 0;
mapTileScript.xGridValue = xLocation;
mapTileScript.zGridValue = zLocation;
}
}
Answer by Simon-Larsen · Mar 26, 2014 at 07:16 PM
What you wanna do is instantiate your GameObject as a GameObject and not as a Transform. Changing line 11 from
mapTile = Instantiate (mapTilePrefab, new Vector3(xLocation, 1, zLocation), Quaternion.identity) as Transform;
to
mapTile = Instantiate (mapTilePrefab, new Vector3(xLocation, 1, zLocation), Quaternion.identity) as GameObject;
Should fix your error message. After you do that, you need to remember to change your "mapTile" variable type to GameObject instead of Transform as well. Hope it helps! :)
When I do that, I end up with this: error CS1061: Type UnityEngine.GameObject' does not contain a definition for
FindChild' and no extension method FindChild' of type
UnityEngine.GameObject' could be found
I've also tried changing FindChild to just Find and I get this: error CS0176: Static member `UnityEngine.GameObject.Find(string)' cannot be accessed with an instance reference, qualify it with a type name ins$$anonymous$$d
Edit: Sorry, this is referring to the next line. Do you know how I would fix then next one? I was hoping casting as transform would fix this problem which is why I was using transform in the first place.
If mapTile is a GameObject use mapTile.transform.FindChild()
Your answer

Follow this Question
Related Questions
iTween NullReferenceException error 1 Answer
Code works in Editor but not in standalone 1 Answer
Functions work in the Editor, don't work when Built. (Javascript) 0 Answers
nullrefernceexception 0 Answers