- Home /
Create a Pause In A For Loop
I am currently trying to create a pause in my for loop so that it wait's X seconds before looping again. The reason for this is I will being picking 20 blocks and sending a ball to hit those 20 blocks but I want a pause in between this since I am using the ball to hit every block and I want it to take some time to happen.
int countUpTo = 5;
float waitTime = 5;
for (int i; i <= 19; i++) {
numbers = GameObject.FindGameObjectsWithTag ("num");
index = Random.Range (0, numbers.Length);
pickedNumber = numbers [index];
print ("number picked");
print (pickedNumber.name);
transform.position = new Vector3 (0, 0, 0);
print ("numer postion");
print (pickedNumber.transform.position);
ball = GameObject.FindGameObjectWithTag ("ball");
float step = speed * Time.deltaTime;
target = pickedNumber.transform;
ball.transform.position = Vector3.MoveTowards (pickedNumber.transform.position, target.position, step);
print ("ball");
print (ball.transform.position);
//Pause here
yield return new WaitForSeconds(waitTime);
ball.transform.position = new Vector3 (-11.4, .3299, -20.63);
}
Comment
Best Answer
Answer by _joe_ · Apr 15, 2015 at 03:08 PM
Your code is ok, just make sure it's inside a coroutine and start that coroutine using StartCoroutine("CouroutineName");
void Start(){
StartCoroutine("MyCoroutine");
}
IEnumerator MyCoroutine(){
int countUpTo = 5;
float waitTime = 5;
for (int i; i <= 19; i++) {
numbers = GameObject.FindGameObjectsWithTag ("num");
index = Random.Range (0, numbers.Length);
pickedNumber = numbers [index];
print ("number picked");
print (pickedNumber.name);
transform.position = new Vector3 (0, 0, 0);
print ("numer postion");
print (pickedNumber.transform.position);
ball = GameObject.FindGameObjectWithTag ("ball");
float step = speed * Time.deltaTime;
target = pickedNumber.transform;
ball.transform.position = Vector3.MoveTowards (pickedNumber.transform.position, target.position, step);
print ("ball");
print (ball.transform.position);
//Pause here
yield return new WaitForSeconds(waitTime);
ball.transform.position = new Vector3 (-11.4, .3299, -20.63);
}
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Foreach Statement Random Sequence/Order? 3 Answers
Distribute terrain in zones 3 Answers
Glitch in Monodevelop for loops!!! 1 Answer
Pause movement on collision 2 Answers