- Home /
For loop update variables value before functions complete
Hi everyone, I'm currently stuck in a situation like this: I have a Script with 3 functions to move my Object in the following order (rotate, move up, and move forward) follow a list of Vector3 coordinates. Each function uses a Vector3 point to work. My goal is to move my object to each target point of the list using the action set above (reset the process after the object has reached a target point). When I test with each individual point, everything works normally However, when I put the list of target points in a for loop to access each elements, the objects immediately move to the last position instead of going through every point of the list Is there a solution for this problem, I've been stuck with this problem for days :(
public void ObjectPathFollowing(List<Vector3> v)
{
for(i = 0; i < v.Count; i++)
{
if(state == 0)
{
Rotation(v[i]);
}
if(state == 1)
{
MovingUp(v[i]);
}
if(state == 2)
{
MovingFoward(v[i]);
}
}
}
Answer by smark12007 · Jul 22, 2020 at 06:30 PM
Maybe you need to wait for seconds?
public void ObjectPathFollowing(List<Vector3> v)
{
StartCoroutine(ObjectPathFollowingEnumerator(v));
}
System.Collections.IEnumerator ObjectPathFollowingEnumerator(List<Vector3> v)
{
for (i = 0; i < v.Count; i++)
{
if (state == 0)
{
Rotation(v[i]);
}
if (state == 1)
{
MovingUp(v[i]);
}
if (state == 2)
{
MovingFoward(v[i]);
}
yield return new WaitForSeconds(0.2f);
}
}
Hi smark12007, Thank you for your solution, it really helps me a lot Following your solution, I've adjusted my code and the object had started to move However, it only moved to the first point of the list and stop Do you know how to fix that?
You might need to show more details of your scripts. Like: Where the program calls ObjectPathFollowing. How state works. Why i is not declared inside the function.
Answer by Weaver13 · Jul 23, 2020 at 04:06 AM
Classes make everything so much nicer. Untested but more or less what I always do.
public class Navigation{
Transform player;
vector[] points;
int index = 0;
public void update(){
float distance = Vector3.Distance(player.position, points[index];
if (distance < 0.1f) index += 1;
if (index >= points.Length) index = 0; //or whatever, maybe choose new array to work on
Vector3 dirToMove = points[index] - player.position;
player.MoveForwardOrUpOrWhatever(dirToMove.normalized * speed);
}
public Navigation(MyMonoBehaviourPlayer, params Vector3[] stuffids){
player = MyMonoBehaviourPlayer.transform;
points = stuffids;
}
}
public class MyMonoBehaviourPlayer : MonoBehaviour{
public Navigation nav;
puvlic void Start(){
nav = new Navigation(this);
}
public void FixedUpdate(){
if (nav != null) nav.update();
}
}
If you are moving the exact amount to the position every frame, then simply add 1 to index every update instead of checking for distance to player.