Performing NPC movement with a function.

I am working on a function for a patrolling NPC’s, but I’ve run into some issues. When I had the code in my Update() block, it worked fine, but now it is not updating key variables, and I am sure it is just because I’m not making use of the variables persistently. Here’s some code:

void patrolling(Transform[] waypointAI, int currentWaypointAI, Vector3 targetAI, Vector3 moveDirectionAI, Vector3 velocityAI, float speedAI) {
				
		wpLengthGUI.text = waypointAI.Length.ToString();
		methodStateGUI.text = "Method Started";
		methodCWP.text = currentWaypointAI.ToString();
		
		
		if (currentWaypointAI < waypointAI.Length) {
			methodStateGUI.text = "Inside first IF";
			
			targetAI = waypointAI[currentWaypointAI].position;

			moveDirectionAI = targetAI - transform.position;
			
			velocityAI = rigidbody.velocity;
		} else {
			methodStateGUI.text = "Inside first ELSE";
			
			currentWaypointAI = -1;	
		}
		
		if (moveDirectionAI.magnitude < .1) {
			
			methodStateGUI.text = "Inside second IF";
			currentWaypointAI = currentWaypointAI ++;
			
		} else {
			methodStateGUI.text = "Inside second ELSE";
			velocityAI = moveDirectionAI.normalized * speed;
		}
		//methodStateGUI.text = "Outside IFs, end ";
		rigidbody.velocity = velocityAI;
	}

What happens when I run this as a callable function is that currentWaypointAI is never incremented, even though my NPC is clearly less than .1 units away. Anyone have any insight into this?

Hi, Dont use moveDirectionAI.magnitude < .1 This returns higher value as it computes direction and converts it int scalar quantity use Vector3.distance or just change .1 to some higher value(approx 6)

Functions pass by value (by default). You’re changing only your local copy of currentWaypointAI.

You can either pass by ref:

Update() { int argument = 0; Function( ref argument ); Debug.Log(argument); }

Function(ref arg) { arg++; }

Or declare your variable as a class member and don’t pass it at all.