Problem instantiating a prefab, and storing a reference to it.

I have the following code…

GameObject go = Instantiate(Balloons[x],transform.position,transform.rotation) as GameObject;
Debug.Log (go);

The object get instantiated just fine, but the Debug.Log shows go is NULL.

The Balloon array does contain prefabs. What is confusing me is that the object IS getting instantiated. I see the balloon on the screen. The code is instantiating the balloon, then trying to assign some values. When I got a null reference during the assignment, I added that Debug.Log line, to make sure that “go” was assigned the object, to decide if the null reference was accessing the component on the object, or if it was the object itself.

Below is the entire routine, in case I am missing something elsewhere.

for (int x=0; x<=BalloonsToSpawn.Count-1; x++){
				if( BalloonsToSpawn[x]>0){
					int a = Random.Range (1,2500);
					if (a<SpawnChance[x]){
						BalloonsToSpawn[x]-=1;						
						GameObject go = Instantiate(Balloons[x],transform.position,transform.rotation) as GameObject;
						Debug.Log (go);
						go.GetComponent<Balloon>().BalloonID = BalloonID;
						BalloonID+=1;						
					}
				}
			}

Any idea what I am doing wrong here?

Any help is appreciated.
-Larry

What type is the Balloons array? It should be GameObject. Even though “as GameObject” is the best way, try to cast instead it will throw an error if there is a problem.

Glad I could help :smiley: