So I have a script which creates a 2D array of GameObjects and then attaches a script
#pragma strict
var mapSize:int;
var map:GameObject;
var mapArray = new GameObject[10,10];
function Start ()
{
// build the map
map = GameObject.Find("Map");
var meshSize = map.renderer.bounds.size;
for(var i:float = 0.0; i < mapSize; i++)
{
for(var j:float = 0.0; j < mapSize; j++)
{
var mapTile = GameObject.CreatePrimitive(PrimitiveType.Plane);
mapTile.transform.localScale = Vector3(.1,0,.1);
mapTile.transform.position = Vector3(i-(mapSize/2),0,j-(mapSize/2));
mapTile.AddComponent("MapTileScript");
mapTile.name = "Tile"+i.ToString()+j.ToString();
mapArray[i,j] = mapTile;
}
}
}
The script attached to the objects created looks like this
#pragma strict
var tile:MapTile;
Debug.Log(tile.type);
function Start ()
{
}
function Update ()
{
}
MapTile is a custom class created in a separate script which looks like this
#pragma strict
public class MapTile
{
var x:float;
var y:float;
var type:String;
var content:String;
}
When I run the game I can look in the inspector and see that the objects were created with the script attached containing the variable with the four components, but when I try to access on of those four components like this…
Debug.Log(tile.type);
I get the error
NullReferenceException: Object reference not set to an instance of an object.
The error only occurs when the script is attached to a GameObject which the ‘AddComponent’ function.
I am completely stumped and would really appreciate some help on this.