var dropObject : Transform;
function Update() {
spawnPos = Random.Range(-2.5, 2.5);
transform.position = Vector3(spawnPos,1,0);
spawnBox();
}
function spawnBox() {
Instantiate(dropObject, transform.position, transform.rotation);
WaitForSeconds (5);
}
So right now I’m trying to instantiate a box (falls down) based on the location of another box that is being placed at random positions. However I only want it to instantiate every few seconds. This script is attached to a box, and I assume update will be executed every frame, but when I call my coroutine within the update shouldn’t it stop it for 5 seconds? Do I need to use a loop within the update()?
I’m having problems grasping the basic concepts of unity.
Just to clarify, Update runs every frame no matter what. You can’t stop it or delay it. So you are calling the SpawnBox function every frame, which spawns a box every frame. Also, WaitForSeconds needs to be used in conjunction with the yield statement; on its own, it won’t do what you want. But even if it was yielding, it would just wait 5 seconds and do nothing. So you’d very quickly have a large number of SpawnBox routines running simultaneously, all of them just waiting around 5 seconds after spawning the box before ending.
So, yep, InvokeRepeating is normally the way to go for things like this. However, you could also write it like so:
var dropObject : Transform;
function Start() {
while (true) {
var spawnPos = Random.Range(-2.5, 2.5);
transform.position = Vector3(spawnPos,1,0);
Instantiate(dropObject, transform.position, transform.rotation);
yield WaitForSeconds (5);
}
}
One advantage of doing it this way compared to InvokeRepeating is that you could yield for a random amount of time if you wanted.