| | | 1 | | /* |
| | | 2 | | * |
| | | 3 | | * Code by: |
| | | 4 | | * Dimitrios Vlachos |
| | | 5 | | * djv1@student.london.ac.uk |
| | | 6 | | * dimitri.j.vlachos@gmail.com |
| | | 7 | | * |
| | | 8 | | */ |
| | | 9 | | |
| | | 10 | | using System.Collections; |
| | | 11 | | using System.Collections.Generic; |
| | | 12 | | using UnityEngine; |
| | | 13 | | |
| | | 14 | | public class MusicManager : MonoBehaviour |
| | | 15 | | { |
| | | 16 | | [Header("Music")] |
| | | 17 | | [SerializeField, Tooltip("List of music to cycle through")] |
| | | 18 | | List<AudioClip> inGameMusic; |
| | | 19 | | [SerializeField] AudioSource audioSource; |
| | | 20 | | |
| | | 21 | | private int songRotation; |
| | | 22 | | void Start() |
| | 1 | 23 | | { |
| | 1 | 24 | | audioSource = GetComponent<AudioSource>(); |
| | | 25 | | |
| | | 26 | | // Select random starting song |
| | 1 | 27 | | int randomSong = Random.Range(0,inGameMusic.Count); |
| | 1 | 28 | | songRotation = randomSong; |
| | | 29 | | |
| | 1 | 30 | | StartCoroutine(PlayMusic()); |
| | 1 | 31 | | } |
| | | 32 | | |
| | | 33 | | IEnumerator PlayMusic() |
| | 1 | 34 | | { |
| | | 35 | | // Get the next clip to play |
| | 1 | 36 | | AudioClip clip = inGameMusic[songRotation]; |
| | | 37 | | |
| | | 38 | | // Play selected song |
| | | 39 | | //Debug.Log("Now playing... " + clip.name); |
| | 1 | 40 | | audioSource.clip = clip; |
| | 1 | 41 | | audioSource.Play(); |
| | | 42 | | |
| | | 43 | | // Increment to select the next song |
| | 1 | 44 | | songRotation++; |
| | | 45 | | |
| | | 46 | | // If we've incremented too far, loop back around |
| | 1 | 47 | | if (songRotation >= inGameMusic.Count) |
| | 0 | 48 | | { |
| | 0 | 49 | | songRotation = 0; |
| | 0 | 50 | | } |
| | | 51 | | |
| | | 52 | | // Get the length of the selected song |
| | 1 | 53 | | float songLength = clip.length; |
| | | 54 | | //Debug.Log("Waiting " + songLength + " until next song..."); |
| | | 55 | | |
| | | 56 | | // Wait that long before playing the next one |
| | 1 | 57 | | yield return new WaitForSeconds(songLength + 1); |
| | | 58 | | |
| | | 59 | | // Play the next song! |
| | | 60 | | //Debug.Log("Looping back!"); |
| | 0 | 61 | | StartCoroutine(PlayMusic()); |
| | 0 | 62 | | } |
| | | 63 | | } |