How to randomly generate objects at a controlled pace in the Update()

Hey,

I am trying to have spawnpoints follow my player at a certain distance and stay at the same y value but change in x value the same as the players x value.

Also right now it spawns thousands of the clouds because it is in the Update(). I know why but I just don’t know where to put the random number generator outside of the Update() to yield WaitForSeconds(1);

Heres the code :

#pragma strict

var spawnPoint1 : Transform;
var spawnPoint2 : Transform;
var spawnPoint3 : Transform;
var cloud : GameObject;
var cloudType = 3;

function Start () {

}

function Wait(time : float) {
	yield WaitForSeconds(time);
}

function Update () {

	cloudType = Random.Range(1,4);
	
	print(cloudType);
	
	switch (cloudType) {
	case (1) :
	Instantiate (cloud, spawnPoint1.position, Quaternion.identity);
	break;
	
	case (2) :
	Instantiate (cloud, spawnPoint2.position, Quaternion.identity);
	break;
	
	case (3) :
	Instantiate (cloud, spawnPoint3.position, Quaternion.identity);
	break;
	
	

}
	Wait(1);
}

Hi, there!
First of all, Update() method is not support coroutines, so you cannot call “yield WaitForSeconds(time)” there.

I recomend you to make 2 changes in your script:

  1. Place code responsible for instantiation in separated method, for example “CreateCloud()”.
  2. Call InvokeRepeating(“CreateCloud”, 1, 100000) at Start() method. See docs here: Unity - Scripting API: MonoBehaviour.InvokeRepeating

So, it should be something like this:

    #pragma strict
     
    var spawnPoint1 : Transform;
    var spawnPoint2 : Transform;
    var spawnPoint3 : Transform;
    var cloud : GameObject;
    var cloudType = 3;
     
    function Start () {
        InvokeRepeating("CreateCloud", 1, 100000);
    }

    function CreateCloud() {
        cloudType = Random.Range(1,4);
       
        print(cloudType);
       
        switch (cloudType) {
        case (1) :
        Instantiate (cloud, spawnPoint1.position, Quaternion.identity);
        break;
       
        case (2) :
        Instantiate (cloud, spawnPoint2.position, Quaternion.identity);
        break;
       
        case (3) :
        Instantiate (cloud, spawnPoint3.position, Quaternion.identity);
        break;
    }

And then I would put the yield WaitForSeconds(1); after that function? That makes sense im new to using these functions. Im usually the modeling guy haha.

EDIT : Nvm i got it. So the invokeRepeating does the yield waitforseconds but just in a timer sort of way. Thanks again.