(Unity)正順のループ/逆順のループ

(スクリプト)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class LoopNumber : MonoBehaviour
{
    private int[] numbers = { 0, 1, 2, 3, 4 };
    private int index;

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Z))
        {
            // ★正順のループ
            index = (index + 1) % numbers.Length;

            print(numbers[index]);
        }

        if (Input.GetKeyDown(KeyCode.X))
        {
            // ★逆順のループ
            index = (index - 1 + numbers.Length) % numbers.Length;

            print(numbers[index]);
        }
    }
}

(実行結果)

<正順>

 

<逆順>