Advice on how to stop a waypoint movement at specified waypoint.

Hey All -

Hopefully a quick question. I wrote a script following a video to create a basic waypoint system for an object to follow. I’d like it to stop at the last waypoint, it currently loops so it’s continuously going in order of its waypoints. I’ve tried adding a trigger to disable the script as well as messing with the script itself to no avail.

I assume there is a simple fix that I’m not aware of - any advice on how to amend the script to make it stop at a set waypoint would be great. Thanks thanks!

  • Will

Script in current form (C#):

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AtoB : MonoBehaviour {
    public GameObject[] waypoints;
    public int num = 0;
    public float minDist;
    public float speed;
    public bool rand = false;
    public bool go = true;
    public GameObject ScriptHolder;

 void Start () {ScriptHolder.GetComponent<AtoB>().enabled = false;}

    void Update () {
        float dist = Vector3.Distance(gameObject.transform.position, waypoints[num].transform.position);
        if (go)
        {
            if (dist > minDist)
            {
                Move();
            }
            else
            {
                if (!rand)
                {
                    if (num + 1 == waypoints.Length)
                    {
                        num = 0;
                    }
                    else
                    {
                        num++;
                    }
                }
                else
                {
                    num = Random.Range(0, waypoints.Length);
                }
            }
        }
 }
    public void Move()
    {
        gameObject.transform.LookAt(waypoints[num].transform.position);
        gameObject.transform.position += gameObject.transform.forward * speed * Time.deltaTime;
    }
}

3396725–267282–AtoB.cs (1.46 KB)

Please look at this thread for how to post code nicely on the forums (and edit your post) : Using code tags properly

1 Like

This is the code that is looping:

if (num + 1 == waypoints.Length)
{
   num = 0;
}
else
{
    num++;
}

Change it to this:

if (num + 1 == waypoints.Length)
{
   go = false
}
else
{
   num++;
}

This will cause your initial if (go) at the start of your Update function to be false once you reach the end of your waypoints

1 Like

Thank you!

Fixed. Thanks.