Space-Smash-Out/Assets/Scripts/AudioLibrary.cs
Jakob Feldmann 6d89d9d48e fix: introduced assetbundles, instead of reading from folder
Reading Assets from folders was only possible in Editor over  LoadAssetFromPath. Now I'm using asset bundles for ScriptedObjects and Audio Prefabs, when the project is built.
When in Editor the folders are still used for convenience (can make changes to assets without rebuilding asset bundles)
2024-04-18 20:23:17 +02:00

70 lines
1.8 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 audioAssetsBundleName = "audio";
public string manageableAudioFolder = "Assets/Prefabs/Audio";
public void Awake()
{
LoadAvailableSounds();
}
/// <summary>
/// Loads all ManageableAudioPrefabs from an asset bundle if built or
/// from the assets folder when in editor.
/// TODO: DO NOT FORGET TO manually BUILD ASSET BUNDLES WHEN BUILDING
/// </summary>
private void LoadAvailableSounds()
{
#if UNITY_EDITOR
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!");
}
}
#else
var audioAssetBundle = AssetBundle.LoadFromFile(Path.Combine(Application.streamingAssetsPath, audioAssetsBundleName));
if (audioAssetBundle == null)
{
Log.Error("Failed to load arenas asset bundle!");
return;
}
List<GameObject> gos = new List<GameObject>();
gos.AddRange(audioAssetBundle.LoadAllAssets<GameObject>());
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!");
}
}
#endif
}
}