Instantiating children in loop not working

Hello, I have tried to instantiate these prefabs in a loop as children of an object that already exists in the scene called “LevelLoad”. For some reason, it only renders a single object instead of the several hundred I’m expecting.

These objects are created by using a 2D map (which I’ve already implemented and it works great) to make a “tiled” area.

I honestly have no idea why it isn’t working. When I run it without trying to parent any of the objects they all appear correctly, it seems to be something to do with my parenting. It comes up with this error on the line:

	go.transform.parent = parentGameObject.transform;

“NullReferenceException: Object reference not set to an instance of an object”

Here is my code, please take a look. If you need more details, please say so :smiley:

	void Start () {
		//parentGameObject = new GameObject();
		Debug.Log ("Locate parent object");
		parentGameObject = GameObject.Find("LevelLoad");
		Debug.Log ("Parent object located. Name: " + parentGameObject.name);

And here is the section from the LoadROSMap() method

		// load map from path
		if(map != null)
		{
			// create bitmap from image
			Debug.Log ("Creating bitmap from map iamge");
	 		Bitmap rosMap = new Bitmap(map);
			Debug.Log ("Bitmap Props: x: " + rosMap.Width + " y: " + rosMap.Height);
		
			
			
			// lets try the getpixel method
			for(int y =0 ; y < rosMap.Height; y++)
			{
				for(int x = 0; x < rosMap.Width; x++)
				{
			 		if(rosMap.GetPixel(x, y) == black)
					{			
						
						GameObject go = Instantiate(wallObject, new Vector3(x,0,y), Quaternion.identity) as GameObject;
						
						if(parentGameObject)
							go.transform.parent = parentGameObject.transform;
						Debug.Log("Instantiating wall object: " + x + ", " + y);
						
					}
						// draw me a cube at these co-ords
						//if(rosMap.GetPixel(x, y) == white)
					//{
						//Instantiate(floorObject, new Vector3(x,0,y), Quaternion.identity);
					//}
							// draw me a plane at these co-ords
							//if(rosMap.GetPixel(x, y) == black)
								// do nothing
				}
			}
		}
		else
			Debug.Log("Failed to read PGM image");

How have you declared wallObject? What type of variable is it?

2 Answers

2

So one of two things is happening:

(1) You have declared the variable wallObject as something other than GameObject.

Instantiate makes an object of the type of variable that the prefab is stored in. For example if the wallObject is stored in a Transform variable then you must do:

 Transform t = Instantiate(wallObject, new Vector3(x,0,y), Quaternion.identity) as Transform;

(2) The game object “LevelLoad” was not found for some reason (incorrect spelling, object disabled etc).

Step 1 worked perfectly! I don’t know how I didn’t see that before, I had tried to use Transform before but I don’t think I had put the identifier “as Transform” on the end.

Thankyou so much :smiley: