Space-Smash-Out/Assets/Scripts/AudioLibrary.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

44 lines
1.0 KiB
C#

using System.Collections.Generic;
using System.IO;
using System.Reflection;
using log4net;
using UnityEditor;
using UnityEngine;
public class AudioLibrary : MonoBehaviour
{
private static ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
public List<GameObject> audios;
public string manageableAudioFolder = "Assets/Prefabs/Audio";
public void Awake()
{
LoadAvailableSounds();
}
/// <summary>
/// Loads all the ManageableAudio prefabs from the specified folder.
/// </summary>
private void LoadAvailableSounds()
{
string[] files = Directory.GetFiles(manageableAudioFolder, "*.prefab",
SearchOption.TopDirectoryOnly);
List<GameObject> gos = new List<GameObject>();
foreach (var file in files)
{
gos.Add(AssetDatabase.LoadAssetAtPath<GameObject>(file));
}
foreach (GameObject go in gos)
{
if (go.TryGetComponent<ManageableAudio>(out _))
{
audios.Add(go);
}
else
{
Log.Warn("Audio library can only load prefabs with ManageableAudio components!");
}
}
}
}