- Home /
Random instantiation endlessly?
I have gameobjects in a list, from which I want to instantiate. However I'm not sure how to actually instantiate a random item from the list, and how to get this thing to run endlessly, so that the game produces a continuous stream of random instantiations (at a desired rate).
               Comment
              
 
               
              Answer by unity_ek98vnTRplGj8Q · Feb 05, 2021 at 05:03 PM
Something like this should do the trick.
 public List<GameObjects> objectsToSpawn;
 public float timeBetweenSpawns;
 public Transform spawnPoint;
 
 private float timer;
 
 void Start(){
     timer = timeBetweenSpawns;
 }
 
 void Update(){
     timer -= Time.deltaTime;
 
     if(timer < 0){
         timer = timeBetweenSpawns;
 
         SetNewSpawnPosition();
         
         int spawnIndex = Random.Range(0, objectsToSpawn.Count);
         Instantiate(objectsToSpawn[spawnIndex], spawnPoint.position, spawnPoint.Rotation);
     }
 }
 
 void SetNewSpawnPosition(){
     //Change the location of the spawn point however you want
 }
If you wanted to be super efficient here you could look into object pooling which is a great optimization for spawning objects like this, but this should serve as a good prototype script.
Your answer
 
 
              koobas.hobune.stream
koobas.hobune.stream 
                       
               
 
			 
                