Yield after spawning object

Hey everyone,

I’m making a simple arcade-style collection game where apples fall and the player has to collect them. The apples fall from a random point (an array of empty gameObjects to simulate a tree), and then are supposed to wait a varying amount of seconds before dropping again.

I thought the code below would work, but the yield command seems to cause the method to not run (everything else runs fine). Of course, removing the yield command results in a million spheres spawning everywhere. Any suggestions? The method as I have it is supposed to spawn another apple in a time frame of 1 to 5 seconds, using Random.Range to select the specific pause length.

function Update () { 
makeApple();
yield WaitForSeconds(Random.Range(1, 5));
}

function makeApple(){
currentApple = Random.Range(0, apple.Length);
var newApple : GameObject = GameObject.CreatePrimitive(PrimitiveType.Sphere);
newApple.transform.position = apple[currentApple].transform.position;
newApple.AddComponent("Rigidbody");
}

You cannot use yield WaitForSeconds in the update.

That is your problem.
As you call the function in the update no matter what you shuld use a timer instead. See below:

function Update () { 
makeApple();
}

function makeApple(){
currentApple = Random.Range(0, apple.Length);
var newApple : GameObject = GameObject.CreatePrimitive(PrimitiveType.Sphere);
newApple.transform.position = apple[currentApple].transform.position;
newApple.AddComponent(Rigidbody);
var wait=Random.Range(1, 5); // Note this is giving 1 to 4. Range excludes the max value when using integers
yield WaitForSeconds(wait);
}

This is calling the function 60 or more time per second and each call is waiting but with:

var timer:float;
var wait:int;
function Start(){
  wait = Random.Range(0,5);
}
function Update(){
  timer+=Time.deltaTime;
  if(timer>wait){
    makeApple();
    wait = Random.Range(0,5);
    timer = 0;
  }
}

function makeApple(){
    currentApple = Random.Range(0, apple.Length);
    var newApple : GameObject = GameObject.CreatePrimitive(PrimitiveType.Sphere);
    newApple.transform.position = apple[currentApple].transform.position;
    newApple.AddComponent(Rigidbody);
    var wait=Random.Range(1, 5);
}

now the function is not called until timer reaches the value