Wait Question

Hi all,

When teaching young students it can be difficult to explain the following code and I’m wondering if there may be an easier way to write this - perhaps using wait or waitforseconds which would remove the need for the additional variables and Time.time business:

var ball : GameObject;
var nextspawn : float=0.0;
var spawninterval : float=0.5;
function Update () {
	
	if (Time.time>nextspawn){
		nextspawn=Time.time+spawninterval;
		Instantiate(ball,transform.position,transform.rotation);
	}
	
}

Any thoughts on ways to simplify the above (for teaching purposes) would be appreciated.

Thanks

Jeff

If students can’t understand the code as it is, perhaps psuedo code is the way to go?

Something like:

function Update () { 
    
   if ( currentTime > timeOfNextSpawn){ 
      // Update time of next spawn
      timeOfNextSpawn = currentTime + spawnInterval; 
      
      // Create a new ball
      CreateNewBall();
   } 
    
}

Comments would also help the students!

var ball : GameObject; 
var spawnInterval : float = 0.5;

function Start () {
   InvokeRepeating ("Spawn", .01, spawnInterval);
}

function Spawn () {
   Instantiate (ball, transform.position, transform.rotation);
}

(I used .01 there because InvokeRepeating seems to have issues with 0.0).

–Eric

Eric, can InvokeRepeating run faster than Update? i.e. Is it run as it’s own thread?

Thanks very much for the ideas.

The Invoke concept should be perfect.

I thought I’d seen a script recently which simply used an Instantiate followed by a wait(2) or something like that - is that possible?

Thanks

Jeff

Yes and no. (Yes, you can make it run faster than Update, but no, it’s not technically a separate thread.)

var ball : GameObject; 
var spawnInterval : float = 0.5; 

function Start () { 
   while (true) {
      Instantiate (ball, transform.position, transform.rotation);
      yield WaitForSeconds (spawnInterval);
   }
}

–Eric

Heya Eric5h5,

For my purposes, that last one is perfect and I think the easiest to explain.

Many thanks again

Jeff