# Modulo (Remainder) method for your waypoints

In case anyone was wondering what Rick was talking about when he mentioned modulo arithmetic, here’s what that is: if you remember when you first learned division in grade school, and if it didn’t divide evenly, you had what’s called a “remainder” - the remainder is what is the outcome of a modulo operation (I’ve only ever heard it called “modulo” in the domain of programming - if this exists anywhere else, feel free to point it out!)

The modulo operation is represented with the percent symbol (%). And the reason it works so well here with the waypoint loop is that, as Rick pointed out, you want to go back to waypoint index 0 after reaching the last one.

So given index i of the current waypoint, if you were to divide i+1 by the total number of waypoints, once you reached the end, your division operation would give you 1 with a remainder of 0; otherwise, you would just get 0 with the remainder still being i+1. And conveniently enough, we can reuse transform.childCount to get that total number of waypoints.

So you can use the if statement, as Rick shows, and that will work. But if you want a more concise operation, you can simply put this into your GetNextIndex() function:

``````return (i + 1) % transform.childCount;
``````

Come to think of it, you may not even need a separate method in that case - you could just put that in the for loop and have the PatrolPath script be that much cleaner.

Hope that clarifies things for anyone who’s interested!

3 Likes

you could also use

``````                int j = (i < transform.childCount-1) ? i+1 : 0;
``````