repeat object spawn

How do I make a prefab spawn repeatedly? Here's my prefab spawn script

var evilsphere : Transform;

function Start () {

yield WaitForSeconds (1); Instantiate (evilsphere, transform.position,
transform.rotation); 

} 

Yes, Unity 5.x requires universal bundles.

–

3 Answers

3

Use InvokeRepeating:

var evilsphere : Transform;
var waitTime = 1.0;

function Start () {
   InvokeRepeating ("Spawn", waitTime, waitTime);
}

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

This previous question answers your question:

http://answers.unity3d.com/questions/14913/programming-help-with-instantiate/14934#14934

Sorry, but I haven't touched XCode since 2011 and I don't remember.

–

The idea to use yield is correct. But you will have to use this in a Coroutine to work.

var evilsphere : GameObject;

function Start () {
  SpawnRoutine();
}

function SpawnRoutine () {
  while(true) {
    Instantiate (evilsphere, transform.position, transform.rotation);
    yield WaitForSeconds(1);
  } 
}

That doesn't make the prefab spawn repeatedly, and you can just use Start for coroutines anyway, no need for a separate function.

–

ups sorry i forgot something...

–

Nice example; how can one check if the previous prefab is dead so that the following one won't spawn on top? you need to check the health of that prefab accessing it's script variable somehow?

–

Yes, just keep a reference to the instantiated Object. You can use it to access the any variable of the attached scripts.

–