revival/game/Assets/Scripts/Audio/AudioManager.cs

91 lines
2.3 KiB
C#
Raw Permalink Normal View History

2021-03-08 16:13:19 +01:00
using System.Collections;
using System.Collections.Generic;
2021-03-24 12:50:07 +01:00
using System.Diagnostics;
2021-03-08 16:13:19 +01:00
using UnityEngine;
using FMOD;
using FMODUnity;
2021-03-24 12:50:07 +01:00
using EventInstance = FMOD.Studio.EventInstance;
2021-03-08 16:13:19 +01:00
[RequireComponent(typeof(FMODUnity.StudioBankLoader))]
public class AudioManager : MonoBehaviour
{
[System.Serializable]
private struct AdjustableAudioBus
{
public string BusName;
public PlayerPrefValue PlayerPref;
public void Initialise()
{
var bus = FMODUnity.RuntimeManager.GetBus( $"bus:/{BusName}" );
PlayerPref.OnFloatSet.AddListener( (vol) => bus.setVolume(vol) );
bus.setVolume( PlayerPref.GetFloat( 1.0f ) );
}
}
[SerializeField]
[EventRef]
private string _musicId;
2021-03-24 12:50:07 +01:00
[SerializeField]
private float _trackDeltaPerSecond;
private const string TRACK_PARAM = "Track";
private float _currentTrack = 1f;
private int _targetTrack = 1;
2021-03-08 16:13:19 +01:00
[SerializeField]
private AdjustableAudioBus _musicBus;
[SerializeField]
private AdjustableAudioBus _sfxBus;
[SerializeField]
private AdjustableAudioBus _voBus;
[SerializeField]
private AdjustableAudioBus _uiBus;
2021-03-24 12:50:07 +01:00
private static AudioManager _instance;
2021-03-08 16:13:19 +01:00
private EventInstance _musicInstance;
2021-03-24 12:50:07 +01:00
public static void SetTrack( int track, bool forceLower = false )
{
if ( forceLower || track > _instance._targetTrack )
{
_instance._targetTrack = track;
}
}
void Update()
{
float dt = Time.deltaTime;
float maxDelta = dt * _trackDeltaPerSecond;
_currentTrack = Mathf.MoveTowards( _currentTrack, (float) _targetTrack, maxDelta );
_musicInstance.setParameterByName( TRACK_PARAM, _currentTrack );
}
2021-03-08 16:13:19 +01:00
void Awake()
{
2021-03-24 12:50:07 +01:00
if ( _instance != null )
2021-03-08 16:13:19 +01:00
{
Destroy( gameObject );
return;
}
2021-03-24 12:50:07 +01:00
_instance = this;
2021-03-08 16:13:19 +01:00
GetComponent<StudioBankLoader>().enabled = true;
_musicInstance = RuntimeManager.CreateInstance( _musicId );
_musicInstance.start();
_musicBus.Initialise();
_sfxBus.Initialise();
_voBus.Initialise();
_uiBus.Initialise();
}
}