Next GameObject In Array

I’m a beginning developer and I followed Blackthornprod’s ‘PATROL AI WITH UNITY AND C# - EASY TUTORIAL’ for one of my projects to understand a bit more about AI, but I need the enemy to go to the next gameobject in the array, instead of it being random. I can’t find any answers online and I need help, here’s the script:

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

public class Patroll : MonoBehaviour
{
    public float speed = 5f;
    private float waitTime;
    public float startWaitTime;

    public Transform[] moveSpots;
    private int randomSpot;


    // Start is called before the first frame update
    void Start()
    {
        waitTime = startWaitTime;
        randomSpot = Random.Range(0, moveSpots.Length);
    }

    // Update is called once per frame
    void Update()
    {
        transform.position = Vector2.MoveTowards(transform.position, moveSpots[randomSpot].position, speed * Time.deltaTime);

        if(Vector2.Distance(transform.position, moveSpots[randomSpot].position) < 0.2f)
        {
            if(waitTime <= 0)
            {
                randomSpot = Random.Range(0, moveSpots.Length);
                waitTime = startWaitTime;
            }
            else
            {
                waitTime -= Time.deltaTime;
            }
        }
    }
}

I think it’s something got to do with ‘randomSpot = Random.Range(0, moveSpots.Length)’

The answer you seek lies in any waypoint patrolling tutorial.

Here’s the essence:

It will involve keeping an integer index into which node you go to next.

You will move towards that node, looking up its position via the index.

When you reach it, you will increment index.

If it exceeds the number of items, set it back to zero.

2 Likes

Well, you’re correct that it’s on that line. All you would need to do is change it from random to incrementing.

2 Likes

So basically, what @Kurt-Dekker and @RadRedPanda say, is to first rename randomSpot to currentSpot (it’s always a good idea (re)name variables to match their functionality). Then just do a currentSpot = currentSpot + 1 (or can be abbreviated to just currentSpot++), then immediately check if currentSpot exceeds your number of spots - 1 (since arrays indices start at 0, not 1), and if it does, revert it to 0 to loop over.

2 Likes

Thank you guys for your time, I got it to work.

2 Likes

Thank you @Nad_B this helped a-LOT

1 Like