- Home /
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
just tested this, works fine for me.. are you sure there's not more you're not telling us?
What exactly are you expecting the debug log to tell you?
maybe go.transform.name?
the as gameobject is pointless by the way. its implicit.
@sparkzbarca - Not so, have you tried this? with UnityScript (JavaScript based) yes, but not with C#!
also, fyi the above debug will return the name of the game object as written (and at any rate you can access the name directly via gameObject... i.e.: "go.name"... so go.transform.name is a bit redundant
What type is the Balloons array? It should be GameObject. Even though "as GameObject" is the best try to cast ins$$anonymous$$d.
Answer by PaulUsul · Nov 16, 2012 at 06:02 PM
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 :D