Can't access Instantiated UI element

Hi, I’ve looked all over but I can’t find a similar problem anywhere!

I’m trying to instantiate a toggle prefab, and make it a child of a canvas and access its postition etc.

Here is my code:

private void SpawnToggle(GameObject[] array){

		GameObject canvas = GameObject.Find("Canvas");

		for(int i = 0; i < array.Length; i++){
			GameObject toggle = Instantiate(togglePrefab) as GameObject;
			toggle.transform.parent = canvas.transform;
		}
	}

The problem is, this line - “toggle.transform.parent = canvas.transform;” Gives me a NullReferenceException.

A toggle will spawn, then it was error. If I remove that line, all my toggles spawn fine. But I cant access them.

Am I missing something really obvious?

I’ve attached the prefab, and everything works until I try and access toggle.

Any Ideas??

Thanks!

What is the type of togglePrefab? A safe cast (as) returns null if the source object cannot be cast to the destination object. Use this line to throw a more meaningful error.

GameObject toggle = (GameObject)Instantiate(togglePrefab);

Instantiating UI elements is alays tricky for me. So I started to use gameObject.SetActive (true); or false.