うにてぃブログ

主にUnityとC#に関する記事を書いていきます

【C#】負の値にも対応したIndexの計算式

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