Проблема, с которой я столкнулся, заключается в том, что в конце первого цикла песни заканчиваются немного раньше, чем они должны быть, вызывая паузу в музыке. Любой цикл после этого звучит правильно.
Код: Выделить всё
using Unity.VisualScripting;
using UnityEngine;
public class MusicManager : MonoBehaviour
{
[SerializeField] AudioClip[] music;
//timeToSwitchTracks is how long to wait before looping and is set to 57.3 seconds
[SerializeField] float timeToSwitchTracks;
AudioSource[] musicSources;
AudioSource[] lastMusicSources;
//selectedMusic determines which song should be audible and which ones should fade out
int selectedMusic = 0;
float timeSinceLastLoop = 0;
private void Awake() {
musicSources = new AudioSource[music.Length];
lastMusicSources = new AudioSource[music.Length];
if(timeToSwitchTracks timeToSwitchTracks) {
createNewAudioSources();
//sets the volume of the newly created audiosource to match the old one
setMusicVolume(lastMusicSources[selectedMusic].volume);
}
}
void updateVolumes() {
int sign = 1;
for(int i = 0; i < musicSources.Length; i++) {
//add to the volume of the selected track, subtract from the volume of all others
sign = i == selectedMusic ? 1 : -1;
//increase or decrease the volume of each song based on if its the selected one or not
musicSources[i].volume = musicSources[i].volume + (Time.deltaTime * sign);
//music sources that are about to be deleted should slowly be muted
if (lastMusicSources[i] != null) {
lastMusicSources[i].volume = lastMusicSources[i].volume - Time.deltaTime;
}
}
}
//creates and starts playing new audiosources for each song
//and puts each precious audiosource into lastMusicSources to fade out slowly
void createNewAudioSources() {
timeSinceLastLoop = 0;
for (int i = 0; i < musicSources.Length; i++) {
//songs placed in this array are slowly muted before being destroyed
lastMusicSources[i] = musicSources[i];
musicSources[i] = transform.AddComponent();
musicSources[i].clip = music[i];
musicSources[i].volume = 0;
musicSources[i].Play();
//the length of each track varies a bit past 57.3 seconds but sound end by 65 seconds
Destroy(musicSources[i], 65f);
}
}
public void setSelectedMusic(int x) {
selectedMusic = x;
}
public void setMusicVolume(float volume) {
musicSources[selectedMusic].volume = volume;
}
}
У меня также возникла еще одна проблема при настройке Для playOnAwake значение true для каждого из аудиоисточников вместо использования метода play() внутри моего метода createNewAudioSource приведет к полному отсутствию воспроизведения звука. Может быть, это может быть связано с этим?
Подробнее здесь: https://stackoverflow.com/questions/790 ... se-after-t