Why my variable increment at start ?

Hello

I have a bug in my script I can’t see

It a simple script to make a character patrolling via waypoints in navmesh, I copied it from the sleath unity tutorial

It’s just in the function “Patrolling”, variable “wayPointIndex” begin at 0 and should stay 0 before the character reach the first waypoint and get the var “newWapoint=true”

But when I start the game “wayPointIndex” always incremente to 1 without the character reach the first waypoint, I can’t see what’s wrong in the code

Here’s the script :

var agent: NavMeshAgent;
var player: Transform;

var patrolWayPoints : Transform[];
private var wayPointIndex : int = 0;
private var newWaypoint : boolean = false;

function Awake () {
	agent = GetComponent.<NavMeshAgent>();
}

function Update () {
	Patrolling ();
	
}

function Patrolling () {

	agent.speed = 1.5;

	if(agent.remainingDistance < 2) //or agent.stoppingDistance
    {
        // If we are close to the waypoint, select the next one
        newWaypoint = true;
    }
    
    if(newWaypoint==true) {
		// Which waypoint is the next
		if(wayPointIndex == patrolWayPoints.Length - 1) { //patrolWayPoints.Length - 1
			wayPointIndex = 0;
			newWaypoint = false;
		} else {
			wayPointIndex++;
			newWaypoint = false;
		}
	}
	
	// Moving to the position
    agent.destination = patrolWayPoints[wayPointIndex].position;
}

Well, i’m pretty sure that you agent doesn’t have a target at the start of your application. That means agent.remainingDistance is probably 0. That means it will set newWaypoint to true and increment the wayPointIndex.

You should assign the current waypoint target first. Either do it once in start, or move the “Moving to the position” line to the beginning of Update.