- Home /
How to Spawn a Prefab over an Array of Transforms, One Prefab at a Time?
Everything is working as it should except my game objects that I want to spawn are all spawning at once instead of one at a time.
Code:
if(i>=whatEverYouWant){
GameObject[] gameObjects = GameObject.FindGameObjectsWithTag("myTag");
Transform[] transforms = new Transform[myArray.Length];
for (int j = 0; j < gameObjects.Length; j++) {
transforms[j] = gameObjects[j].transform;
GameObject myArrayClones = Instantiate (myPrefab, transforms[j].transform.position, transform.rotation) as GameObject;
}
}
Only 1 prefab should be instantiated at transforms[j].transform.position, each time the mouse button is clicked.
Instead they all spawn at once.
What's the simples way to fix this?
Thanks!
Answer by ShinyTaco · Dec 11, 2015 at 06:56 AM
Never mind.
Removed the for loop and added:
if(j<gameObjects.Length){
if(i>=whatEverYouWant){
GameObject[] gameObjects = GameObject.FindGameObjectsWithTag("myTag");
Transform[] transforms = new Transform[myArray.Length];
if(j<gameObjects.Length){
// for (int j = 0; j < gameObjects.Length; j++) {
transforms[j] = gameObjects[j].transform;
GameObject myArrayClones = Instantiate (myPrefab, transforms[j].transform.position, transform.rotation) as GameObject;
}
}
}
Basically had to store GameObjects with "myTag" into an array. Next had to store the transforms from all of the instantiated prefabs into another array. Then cycle through the entire array one mouse click at a time to spawn the new prefabs.
This post also helped a lot, thanks.
Your answer
![](https://koobas.hobune.stream/wayback/20220612052203im_/https://answers.unity.com/themes/thub/images/avi.jpg)
Follow this Question
Related Questions
add spawned GameObjects in an array C# 1 Answer
Problem with spawn custom mesh on prefab terrain 0 Answers
Spawning Objects Using An Array. 1 Answer
Nested Prefab Issue 0 Answers
Creating an array of prefabs? 4 Answers