- Home /
Unity not Instantiating as Prefab
I have this function that instantiates 2 different prefabs and adds both of them to the same list. This is contained in a loop and so it does it multiple times. Here's the code:
void instantiateItems ()
{
for (int i = 0; i <= maxItemTypeCount; i++) {
GameObject tempEgg = Instantiate (egg, new Vector3 (0, -50f, 0), Quaternion.identity) as GameObject;
tempEgg.name = "egg";
availableItems.Add (tempEgg);
GameObject tempCoke = Instantiate (coke, new Vector3 (0, -50f, 0), Quaternion.identity) as GameObject;
tempCoke.name = "coke";
availableItems.Add (coke);
}
}
I also have this bit of code that moves the prefabs into view when they are needed. However, only the "egg" prefab moves when it is told, whilst the "coke" prefab does not move. I've noticed in the inspector during run-time, the prefabs in the list have different icons. For the life of me I can't figure out why they have different icons and I think that is the reason why "coke" doesn't move. Here's some pictures of the list as well as the inspector view of the prefabs:
The "egg" prefab is exactly the same as the "coke" prefab, except for the name of course. When I click the "egg" object in the list during run-time, it actually lights up the "egg" object in the hierarchy view. But when I click the "coke" object in the list, only the "coke" prefab in the project view lights up.
I'm sure there is a super simple explanation, but I can't see it. Any help would be great.
Thanks
First thing i see, you adding the var 'coke' to the list and not the 'tempCoke'. I think that's the problem :)
Answer by Cynikal · Sep 20, 2016 at 06:58 PM
Change:
availableItems.Add (coke);
to:
availableItems.Add (tempCoke);
They are different, because you're adding the prefab to the list on one, and an actual gameobject to the list on another.