Unity 防止数组索引越界的几种方法

%

        简介:如果一个数除以大于它的数那得到的余数(%)就是它本身

        实例:1 ➗ 4 商:0 取余:1

                   2 ➗ 4 商:0 取余:2

                   3 ➗ 4 商:0 取余:3

                   4 ➗ 4 商:1 取余:0

总结:用取余符号得到的数就是取余这块的数

//  数组
int[] wayPoints = new int[4];
//  索引
int wayPointIndex = 0;

//  防止越界【方法1】
wayPointIndex++;
if (wayPointIndex == 4)
    {
        wayPointIndex = 0;
    }


//  防止越界【方法2】
wayPointIndex++;
wayPointIndex = wayPointIndex % wayPoints.Length;


//  防止越界【方法3】
wayPointIndex++;
wayPointIndex &= wayPoints.Length;


//  防止越界【方法4】
wayPointIndex = ++wayPointIndex % wayPoints.Length;

猜你喜欢

转载自blog.csdn.net/qq_24977805/article/details/122588814