- Home /
Using a while loops to repeatedly execute a method?
Okay so the code I provided below is a simplification of my actual code as I felt it would be more reasonable to post a simpler version and hopefully receive some answers that I can apply to my actual, fairly more complex code. Anyway, I am basically trying to use a while loop to repeatedly execute a method such that, on start, the game object that the script is attached to will traverse a smooth path (in this case linear). Below are two of my attempts at doing this. When I run it, the game object will either not move at all or will jump/teleport from start point to endpoint rather than traveling a smooth line from start to end. I do not understand why these do not work... Any ideas?
float b = 0;
void Start () {
while (b < 1) {
Function ();
}
}
void Function () {
x = b + 1;
y = b + 2;
transform.position = new Vector3 (x, y, 0);
b += .01;
}
float b = 0;
void Start () {
while (b < 1) {
transform.position = Function ();
}
}
Vector3 Function () {
Vector3 newPosition;
x = b + 1;
y = b + 2;
newPosition = new Vector3 (x, y, 0);
b += .01;
}
Are you looking for a smooth travel from Point A to Point B?
Answer by fafase · May 06, 2014 at 05:35 AM
you need to look into coroutine. At the moment, when the while loop starts it performs the whole movement within the Start method, so you don't see the progression only the final result.
With a coroutine, you can leave the method at a point and get back there next frame. In between the object is rendered:
void Start(){
StartCoroutine(Move());
}
IEnumerator Move(){
float b = 0;
while (b < 1) {
transform.position = new Vector3 (b + 1, b + 2, 0);
b += .01;
yield return null;
}
}
Answer by TheRaven · May 06, 2014 at 05:33 AM
If you want to have an object animate around you will need to do the position changes in the update function instead of the start function.
So that the object moves the desired amount during an update call and is then rendered in the render call. Then moves more in the next update call and is then rendered in the next render call.
What you have done is move the object before anything is up and running, by the time an update and render is called the object is at the final position.
Your answer
Follow this Question
Related Questions
Quaternion.Slerp issue 1 Answer
Iterator variable not increasing. 1 Answer
How to get something to be inactive while there is a certain value 2 Answers
Display a loading while processing a while loop 1 Answer
While loop freezes unity 3 Answers