- Home /
Game objects missing after instantiating?
I am trying to generate some terrain with the following code:
// Spawn initial rocks. // variable 'rocks' is type List<GameObject> for (int i = 0; i < rockCount; i++) { GameObject rock = Instantiate(Resources.Load("Prefabs/Rock")) as GameObject; rocks.Add(rock); // (Code to reposition goes here, it's not the problem) }
I would think that this generates rockCount number of clones of the rock prefab, but every time I run it it only makes a seemingly random number of them (usually about a quarter rockCount). The for loop is definitely running rockCount times, but the remaining entries in the list rocks fill up with "Missing (Game Object)". I've tried putting this instantiation in a while (rock == null) loop, but that didn't fix it either.
Has this been solved? I have the same problem.,Has this been solved? I have the same problem.
For starters, you should use Resources.Load
only once before the loop and save it to a local variable, then only Instantiate
from the variable.
If possible, you shouldn't even use the Resources folder. Ins$$anonymous$$d, add a public GameObject Prefab;
at the top of the $$anonymous$$onoBehaviour and place the prefab into that.
Answer by Cornelis-de-Jager · Jul 21, 2017 at 12:20 AM
The problem is the way you are loading in the rock prefab. You are not declaring what type of object you are loading. Replace this:
GameObject rock = Instantiate(Resources.Load("Prefabs/Rock")) as GameObject;
With this:
GameObject rock = Instantiate(Resources.Load("Prefabs/Rock", typeof (GameObject))) as GameObject;
Well, now it's doing better; it's getting around 60-80% of the number of rocks it should. There are still a bunch of "$$anonymous$$issing (Game Object)" entries in the list though...