- Home /
Waiting for condition to be met before continuing loop
More specifically, I am trying to run some method on an object in an array, and then waiting for that method to finish before continuing the for loop it's running in. Here's a code example of what I mean:
private void DoActions(StateController controller)
{
for (int i = 0; i < actions.Length; i++)
{
actions[i].Act(controller);
if (sequencialActions)
//Wait for Act() to finish, then continue
}
}
Basically I am trying to do this, so I can have my AI either do all their actions at the same time, or do them one after another, waiting for the prior action to finish before doing the current one.
Any recommendations?
Answer by UnityedWeStand · Aug 09, 2020 at 06:06 AM
If you are executing this code in the context of a single frame update (i.e. within a singled Start() or Update()), then the code will automatically execute in the order it was called. However, this means that the next frame will not come up until ALL of the code has executed.
If you are calling methods that may take multiple frame updates to complete, consider using Coroutines to control execution flow.
Answer by MomkeyDev · Aug 09, 2020 at 04:08 AM
use a while loop in the for loop, which basically will loop your code until the condition is false
for (int i = 0; i < action.length; i++)
{
//the while loop a code as long a condition is met
//
//for this example as long as the object is not in the target position
//the code will loop until it result as false
while (Objectfirstpostition != ObjectTargetPosition)
{
//execute the code until the object reached it's destination
//it would be better to use '<' or '>'syntax
moveobject();
}
}
anyway i wouldn't recommend using while loop, because the loop doesn't execute every frame different fom the update method. if anything goes wrong just reply to me
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Send an enemy back to its spawn point using waypoints 2 Answers
Why is my vector3 value not changing? 1 Answer
How do you CORRECTLY call methods from another C# file 1 Answer