trouble with for each

I am having trouble with for each loop,
here is the loop

   public class map : MonoBehaviour
        {// Use this for initialization
        void Start () {
        		Leaf[] leafs = new Leaf[10];
        		foreach (Leaf l in leafs)
        		{
        			l.leftChild = new Leaf();
        			l.rightChild = new Leaf();
        		}
        }

and hear are the sub leaf defenitions. but for some reason the game tells me 
NullReferenceException: Object reference not set to an instance of an object
map.Start () at l.leftChild = new Leaf();

public class Leaf
{
public Leaf leftChild; // the Leaf's left child Leaf
public Leaf rightChild; // the Leaf's right child Leaf
}

and I am just not sure why its giving me the error. any thoughts are appreciated.

1 Answer

1

Close, but it doesn’t look like your actually putting anything in the array at the start, your just initializing it. So its an array of leafs, but each element is empty. You need to add a leaf to each element of the array before you start the foreach loop.

public class map : MonoBehaviour
{

	public Leaf leafObject;
	public Leaf leafObjectPrefab;

	void Start ()
	{
		Leaf[] leafs = new Leaf[10];

		for(var i = 0; i < leafs.Length; i++)
		{
			leafObject = Instantiate(leafObjectPrefab, Vector3(0,0,0), Quaternion.Euler (0,0,0));
			leafs *= leafObject;*
  •  }*
    
  •  foreach (Leaf l in leafs)*
    
  •  {*
    
  •  	l.leftChild = new Leaf();*
    
  •  	l.rightChild = new Leaf();*
    
  •  }*
    
  • }*
    }