(Unity)ボタンを押してBGMを切り替える(順送り・ループ)

(スクリプト)

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

public class BGMChange : MonoBehaviour
{
    public AudioClip[] sounds;
    private int num = 0;
    private AudioSource audioSource;

    private void Start()
    {
        audioSource = GetComponent<Audiosource>();
        audioSource.clip = sounds[num];
        audioSource.Play();
    }

    void Update()
    {
        if(Input.GetKeyDown(KeyCode.Space))
        {
            int BGMNum = (num + 1) % sounds.Length;

            audioSource.clip = sounds[BGMNum];

            audioSource.Play();

            num += 1;
        }
    }
}

(実行結果)

  • スペースキーを押すごとにBGMが切り替われば成功