- Home /
My prefabs always spawn twice at different positions
So I'm working on a game where I want to randomly spawn different arrangements of blocks as obstacles. I created an empty gameobject as a parent and put the blocks around it as children so I adjust the position properly. Afterwards I created a prefab of this and loaded it into an array so I can randomly choose one in the future. But if I now want to spawn the prefab with a custom position it not only spawns there but also on the position the prefab itself has assigned to. Is there a way to prevent this? My code:
void Start()
{
prefab[0] = GameObject.Instantiate(Resources.Load("prefab1")) as GameObject;
// Instantiate at position (0, 0, 0) and zero rotation.
Instantiate(prefab[0], new Vector3(0, 1, 140), Quaternion.identity);
Instantiate(prefab[0], new Vector3(0, 1, 120), Quaternion.identity);
}
Interestingly I can initiate two objects of the same type but the bug only occurs once.
Answer by SigmarOD · Dec 09, 2020 at 01:53 PM
I just noticed that my declaration to the array contained an initiation command. My question is now if I could put the gameobject into the array without spawning it rightaway.
My current code (only spawns at start tho):
void Start()
{
prefab[0] = GameObject.Instantiate(Resources.Load("prefab1"), new Vector3(0, 1, 140), Quaternion.identity) as GameObject;
}
Perhaps this is what your looking for? https://answers.unity.com/questions/711778/adding-prefabs-to-a-list-or-an-array-from-a-folder.html
no you can't put it in the array before spawning it, can you eat a pizza before getting it? What you can do it store a reference to the prefab and then instantiate it when you want, or use object pooling have have it already instantiated but disabled and then you just enable it when you want it.