55 lines
1.6 KiB
C#
55 lines
1.6 KiB
C#
// Assets/_Project/Scripts/Audio/MusicPlayer.cs
|
|
using UnityEngine;
|
|
|
|
namespace TD.Audio
|
|
{
|
|
/// <summary>
|
|
/// Plays a single looping music track for the scene it lives in.
|
|
/// Add to a GameObject in the scene, assign a clip, and it starts on load.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// Volume is the authored <see cref="volume"/> scaled by the player's music slider
|
|
/// (<see cref="AudioVolumeSettings.MusicScalar"/>). Unlike one-shot SFX, the track is
|
|
/// continuous, so this subscribes to <see cref="AudioVolumeSettings.OnChanged"/> and
|
|
/// re-applies live while the slider is dragged.
|
|
/// </remarks>
|
|
[RequireComponent(typeof(AudioSource))]
|
|
public class MusicPlayer : MonoBehaviour
|
|
{
|
|
[SerializeField] private AudioClip clip;
|
|
[Range(0f, 1f)]
|
|
[SerializeField] private float volume = 1f;
|
|
|
|
private AudioSource source;
|
|
|
|
private void Awake()
|
|
{
|
|
source = GetComponent<AudioSource>();
|
|
}
|
|
|
|
private void OnEnable()
|
|
{
|
|
AudioVolumeSettings.OnChanged += ApplyVolume;
|
|
}
|
|
|
|
private void OnDisable()
|
|
{
|
|
AudioVolumeSettings.OnChanged -= ApplyVolume;
|
|
}
|
|
|
|
private void Start()
|
|
{
|
|
source.clip = clip;
|
|
source.loop = true;
|
|
source.playOnAwake = false;
|
|
ApplyVolume();
|
|
source.Play();
|
|
}
|
|
|
|
private void ApplyVolume()
|
|
{
|
|
if (source == null) return;
|
|
source.volume = volume * AudioVolumeSettings.MusicScalar;
|
|
}
|
|
}
|
|
}
|