GameVsJam/3d Prototyp/Assets/Scripts/MusicManager.cs

104 lines
2.7 KiB
C#
Raw Normal View History

2024-04-07 14:22:27 +02:00
using System;
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;
using Utility;
public class MusicManager : MonoBehaviourSingleton<MusicManager>
{
[SerializeField]
private List<AudioClip> _ambientMusic;
[SerializeField]
private AudioClip _showDownMusic;
[SerializeField, ShowOnly]
private float _musicTimer = 5f;
private float _musicCheckInterval = 30f;
private AudioSource _audioSource;
private AudioClip _currentlyPlaying;
private float _defaultVolume;
private bool _showDownTime = false;
private bool _doneFading = false;
private bool _showDownIsPlaying = false;
// Start is called before the first frame update
void Start()
{
_audioSource = GetComponent<AudioSource>();
_defaultVolume = _audioSource.volume;
}
// Update is called once per frame
void Update()
{
CheckForFinalMusic();
if (!_showDownTime)
{
_musicTimer -= Time.deltaTime;
if (_musicTimer <= 0)
{
_musicTimer = _musicCheckInterval;
if (!_audioSource.isPlaying)
{
PlayNewMusic();
}
}
}
else
{
if (_doneFading)
{
if (!_showDownIsPlaying)
PlayShowDownMusic();
}
else
{
FadeOutMusic();
}
}
}
private void FadeOutMusic()
{
_audioSource.volume -= _audioSource.volume * Time.deltaTime;
_audioSource.volume = _audioSource.volume <= 0.05f ? 0.0f : _audioSource.volume;
_doneFading = _audioSource.volume <= 0.05f;
}
private void CheckForFinalMusic()
{
float timeLeft = (float)GameManager.Instance.ExpectedRemainingGameDuration;
_showDownTime = timeLeft < 0.9 * _showDownMusic.length;
}
private void PlayNewMusic()
{
if (_currentlyPlaying == null)
{
_audioSource.clip = _ambientMusic.GetRandomElement();
_audioSource.Play();
}
else
{
_ambientMusic.Remove(_currentlyPlaying);
AudioClip newMusic = _ambientMusic.GetRandomElement();
_ambientMusic.Add(_currentlyPlaying);
_audioSource.clip = newMusic;
_audioSource.Play();
}
}
private void PlayShowDownMusic()
{
_showDownIsPlaying = true;
_audioSource.Stop();
_audioSource.volume = _defaultVolume;
_audioSource.clip = _showDownMusic;
_audioSource.loop = true;
_audioSource.Play();
}
}