Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make the loop working without keep increment the index nonstop?

When the loop flag is set to true it’s continuing moving between the waypoints nonsotp.

The problem is when the flag loop is set to false then it stop at the last waypoint but then also give exception : ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.

The index is keep raising in the Move function.
I’m not sure how to solve it when the loop flag is false.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Waypoints : MonoBehaviour
{
    public float speed;
    public bool go = false;
    public bool moveToFirstPositionOnStart = false;
    public List<Transform> positions;
    public bool loop = true;

    private int index = 0;

    // Start is called before the first frame update
    void Start()
    {
        if (moveToFirstPositionOnStart == true)
        {
            transform.position = positions[index].position;
        }
    }

    // Update is called once per frame
    void Update()
    {
        if (go == true)
        {
            Move();
        }
    }

    void Move()
    {
        transform.position = Vector3.MoveTowards(transform.position,
                                                positions[index].position,
                                                speed * Time.deltaTime);

        float distance = Vector3.Distance(transform.position, positions[index].position);
        if (distance < 0.01f)
        {
            positions[index].GetComponent<Renderer>().material.color = Color.red;
            index += 1;
        }

        if (index == positions.Count && loop)
        {
            index = 0;
        }
    }
}

>Solution :

Use the following to stop entering Move at the end of your waypoint sequence depending on if loop is disabled or not:

if (index == positions.Count) 
{
    index = 0; 
    go = loop;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading