Space-Smash-Out/Assets/Scripts/ManageableAudio.cs
Jakob Feldmann 5a658d6cd4 feat: audio management/playback features
Every sound in the game is now a ManageableAudio prefab.
The prefabs are picked up in an audio library automatically and other game objects
can get the sound they need from the AudioManager.
They obtain a ManageableAudio instance which offers various
methods to interact with the AudioSource.
Depending on how they request the ManageableAudio, the AudioSource
is attached to the requesting GameObject, to the Scene or the global management Scene.
This provides options to play sounds spatially, globally and scene independent.

The prefabs are identified by a tag and an ID, so it is easy to swap out sounds globally, by just replacing the prefab.
2024-04-10 16:57:25 +02:00

68 lines
1.2 KiB
C#

using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reflection;
using log4net;
using PrimeTween;
using UnityEngine;
public class ManageableAudio : MonoBehaviour
{
private static ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public int id = 0;
public string audioTag = "audio";
public AudioSource AudioSource { get; set; }
void Awake()
{
if (gameObject.TryGetComponent(out AudioSource audioS))
{
AudioSource = audioS;
}
else
{
Log.Warn("Managable Audio Instance hasn't got an audio source game object"
+ $". Tag:{audioTag} ID:{id}");
return;
}
}
public void PlayAudio()
{
if (AudioSource == null)
{
return;
}
if (!AudioSource.enabled)
{
AudioSource.enabled = true;
}
AudioSource.Play();
}
public void StopAudio()
{
if (AudioSource == null)
{
return;
}
if (AudioSource.isPlaying)
{
AudioSource.Stop();
}
}
public void FadeOutAudio(float duration = 1)
{
float initVolume = AudioSource.volume;
Tween.Custom(initVolume, 0, duration, onValueChange: value => AudioSource.volume = value)
.OnComplete(() =>
{
StopAudio();
AudioSource.volume = initVolume;
});
}
}