The simplest way I'd go at it is to remove the modulo operation from this line. It'll be safe to remove the parenthesis too.
Code:
index = (index+direction)%5
It might also help to add a check to break the loop if
index is out of bounds.
Code:
index = index+direction
if index<0 or index>=maxUnits then break end
Note
index appears to be zero-based and has +1 added when generating the UnitID.