- Home /
problem with loop / unity crash
I'm using this code to move an object from one point called "waypoints" to another one and I have a problem to loop this, when I added loop do...while then unity crashed (everything is commented) any idea why or where should I add loop, I was trying several times.
public class FollowThePath : MonoBehaviour
{
//Array of waypoints to walk from one to the next one
[SerializeField]
private Transform[] waypoints;
//Walk speed that can be set in Inspector
[SerializeField]
private float moveSpeed = 2f;
//Index of current waypoint form which Enemy walks to the next one
private int waypointIndex = 0;
//Use this for initialization
private void Start()
{
//Set position of Enemy as position of the first waypoint
transform.position = waypoints[waypointIndex].transform.position;
}
//Update is called once per frame
private void Update()
{
//Move function of Enemy
Move();
}
//Method that actually make Enemy walk
private void Move()
{
//If Enemy didn't reach last waypoint it can move
//If Enemy reached last waypoint then it stops
if (waypointIndex <= waypoints.Length - 1)
{
//Move Enemy from current waypoint to the next one
//using MoveTowards method
transform.position = Vector2.MoveTowards(transform.position,
waypoints[waypointIndex].transform.position,
moveSpeed * Time.deltaTime);
//If Enemy reaches position of waypoint he walked towards
//then waypointIndex is increased by 1
// and Enemy starts to walk to the next waypoint
if (transform.position == waypoints[waypointIndex].transform.position)
{
waypointIndex += 1;
}
}
}
}
Answer by WarmedxMints · Mar 21, 2019 at 08:29 PM
Your problem is here;
if (transform.position == waypoints[waypointIndex].transform.position)
{
waypointIndex += 1;
}
The x, y and z values are floats and it is highly unlikely that they will ever be the same. What you need is a tolerance. So use Vector3.Distance instead with a margin of error in there.
if (Vector3.Distance(transform.position, waypoints[waypointIndex].position) < 0.01f)
{
waypointIndex += 1;
}
Answer by Kirchesch · Mar 21, 2019 at 08:57 PM
Where is your loop?
One thing i can tell you right now, any infinite loop will crash Unity instantly, does not matter if there are or not code on this loop. if you need infinite loop you have to use coroutines
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
For loop not working as intended?!? (Beginner) 1 Answer
Callback from a Loop 1 Answer
C# List looping Vector3's 2 Answers