- Home /
Coroutine Loops
Coroutine Loops
Hi - I'm trying to understand coroutines (I come from Flash where you just run loops or use timers). I looked at this post:
http://answers.unity3d.com/questions/131858/instantiation-at-interval-times.html
but it doesn't seem to address looping. Nor does the documentation for unity - coroutines simply run and then finish. If I try to make a repeat call to the function from within the function, I get an error. Furthermore, if I move certain lines of my code out of update and into the coroutine function, I get errors. All I want to do is have a launcher which fires a projectile at a random interval every 5-10 seconds. This is my code, and I want to replace the dependency on the fire button with an automatic loop.
function Update()
{
if( Input.GetButtonDown( "Fire1" ) ){
var randomAngle:float = Random.Range(120, 180);
var randomRot = Quaternion.Euler(0,Random.Range(-30, 30),-10);
launcherRef.transform.rotation = initialRot * randomRot;
var numRandom:float = (Random.value*objectSizeMax);
//instantiate a projectile and throw it toward the cube (x axis)
var instantiatedProjectile : Rigidbody = Instantiate( projectile, transform.position, transform.rotation ) ;
instantiatedProjectile.transform.localScale = Vector3.one * (numRandom); //I add these two together here because I have no clue what I'm doing
instantiatedProjectile.velocity = transform.TransformDirection( Vector3( speed, 0, 0) );
for (var i=0; i<boundaryRef.length;i++){
Physics.IgnoreCollision( instantiatedProjectile.collider, boundaryRef[i].collider); //make sure to ignore collision between launcher and missile
}
}
};
Answer by Peter G · Jul 14, 2011 at 04:23 PM
If you have a constant interval, then I suggest using InvokeRepeating(), but for a variable time like this I would do something like this.
function Start () {
//Initialize your variables.
ProjectileLaunch();
}
function ProjectileLaunch () :IEnumerator {
while (true) {
//Launch Projectile
yield WaitForSeconds (Random.Range( minTime , maxTime );
}
}
awesome thanks! I was trying to put the while statement within start.
Your answer
Follow this Question
Related Questions
A node in a childnode? 1 Answer
Running multiple coroutines in loops with different time 2 Answers
Play Looped Sound? 4 Answers
How do I loop an animation with Unity 4.3? 5 Answers
Iteration of coroutines 1 Answer