public static class Utility { /// <summary> /// 0~maxの範囲のIndex を返す /// 負の値にも対応 /// </summary> public static int LoopIndex(int index, int max) { var ret = index % max; if (index < 0) ret += max; return ret; } }
実行例
Utility.LoopIndex(10, 20); // 10 Utility.LoopIndex(10, 5); // 0 Utility.LoopIndex(10, 4); // 2 Utility.LoopIndex(-10, 7); // 4