- Home /
 
Instantiate objects in a specific order
I am making 3d endless runner and right now my code generates random floor prefabs(I have 6 of them) from the array at the certain time. But instead of random I want specific prefabs to be generated so the player will be passing through different zones. To be more exact - each prefab from the array should be instantiated 3 times in a row and then the next one and so on. When the loop goes through all the prefabs from the array, it should start again from the 1st prefab.
The code I have now:
 public GameObject[] prefabArray;
 public float spawnTime;
 
 void Start () {    
      Spawn (); 
 }
     
 void Spawn () {    
      Instantiate (prefabArray [Random.Range (0,prefabArray.GetLength(0))], transform.position, Quaternion.identity);    
      Invoke ("Spawn", spawnTime); 
 }
 
              Answer by fafase · May 04, 2014 at 09:32 AM
I would think your guy is not moving and the world is moving towards him, so a level manager would do.
Define a method with a set of parameter that will make things happen in the way you want and call that method at specific time. For instance this below will create 5 objects you define from the array.
 void CreateObject(param int [] list)
 {
    for (int i = 0; i < list.Length; i++)
       Instantiate(array[list[i]], position, rotation);
 }
 void Update()
 {
    if(time == 0)  CreateObject(1,2,3,4,5);
    if (time == 10)CreateObject(1,1,1,2,2,2);
    // And so on
 }
 
              Answer by Koharu · May 04, 2014 at 09:32 PM
Thank you, but unfortunately Unity crushes when I use this code. I've just created new prefabs which consist of few objects(in my case 3 pieces of the floor) and still using my original code.
Your answer
 
             Follow this Question
Related Questions
How can I destroy many instantiated objects on endless game 1 Answer
Trying to not make an infinite loop 0 Answers
Instantiate color change loop 0 Answers
OverlapSphere for parallel arrays 1 Answer
Why does this code hang the system?? 2 Answers