Creating dynamic objects

This will be probably a trivial problem for an experienced programmer but I’m not one of these so here goes. Why the following piece of code throws NullReferenceException?
This script is attached to an empty object and ‘Bulb’ script is attached to a prefab. I’m essentially trying to dynamically create an array of ‘Bulbs’. Is it impossible to create new objects like that?

public class BulbCreator : MonoBehaviour {

	public Transform Bulb;
	public int width, height, spacer;
	public Bulb[,] Bulbs;

	void Start () 
	{
		Bulbs = new Bulb[width, height];
		for (int x = 0; x < width; x++)
			for (int y = 0; y < height; y++)		
				{									
				Bulbs[x,y] = Instantiate(Bulb, new Vector3(x*spacer, y*spacer, 0), Quaternion.identity) as Bulb;
				//Debug.Log ("->"+b);
				Bulbs[x,y].SetPos (x,y); <---- this line throws exception
				}
	}
}

Hello!

You have a Transform variable named Bulb which has the same name as the class Bulb. This makes the code more confusing!

As for why you’re getting a null reference, it is from these two lines.

public Transform Bulb;
// ...
// Null reference here. Transform does not cast as Bulb!
Bulbs[x,y] = Instantiate(Bulb, new Vector3(x*spacer, y*spacer, 0), Quaternion.identity) as Bulb;

The reason is because you are instantiating a Transform, then attempting to cast it as Bulb. Do this instead.

// Not a Transform.
public Bulb bulbPrefab;
// ...
// This time we are passing in a Bulb object to
// instantiate instead of a Transform object.
Bulbs[x,y] = Instantiate(bulbPrefab, new Vector3(x*spacer, y*spacer, 0), Quaternion.identity) as Bulb;

P.S. You can use CODE tags to format your code nicely on the forums.

Thank you so much, works like a charm and it’s clear to me now :slight_smile: