From 12faa0c8a1c563cba4c139749619b267c2890764 Mon Sep 17 00:00:00 2001 From: Nico de Poel Date: Sun, 11 Apr 2021 23:03:27 +0200 Subject: [PATCH] Allow FMOD system to be re-created during hot code compile & reload, and added some debug UI to inspect what FMOD is doing --- Assets/Scripts/AudioManager.cs | 49 ++++++++++++++++++++++++++++++---- 1 file changed, 44 insertions(+), 5 deletions(-) diff --git a/Assets/Scripts/AudioManager.cs b/Assets/Scripts/AudioManager.cs index 212e318..82fa7fe 100644 --- a/Assets/Scripts/AudioManager.cs +++ b/Assets/Scripts/AudioManager.cs @@ -1,6 +1,7 @@ using System; using System.Collections; using System.Collections.Generic; +using System.Text; using UnityEngine; public class AudioManager : MonoBehaviour @@ -31,6 +32,33 @@ public class AudioManager : MonoBehaviour void Awake() { + // Ensure FMOD is initialized the moment Instance is accessed + InitFmod(); + } + + void OnEnable() + { + // Ensure FMOD gets re-initialized after hot reload + InitFmod(); + } + + void OnDisable() + { + // Ensure FMOD gets closed before hot reload + CloseFmod(); + } + + void OnDestroy() + { + CloseFmod(); + instance = null; + } + + private void InitFmod() + { + if (fmodSystem.hasHandle()) + return; + FMOD.RESULT result = FMOD.Factory.System_Create(out fmodSystem); CheckFmodResult(result, "FMOD.Factory.System_Create"); @@ -54,11 +82,6 @@ public class AudioManager : MonoBehaviour result = fmodSystem.init(MaxChannels, FMOD.INITFLAGS.NORMAL, IntPtr.Zero); CheckFmodResult(result, "FMOD.System.init"); } - - void OnDestroy() - { - CloseFmod(); - } private void CheckFmodResult(FMOD.RESULT result, string cause) { @@ -73,9 +96,25 @@ public class AudioManager : MonoBehaviour { if (fmodSystem.hasHandle()) { + Debug.Log("[FMOD] Closing FMOD System"); fmodSystem.close(); fmodSystem.release(); fmodSystem.clearHandle(); } } + +#if UNITY_EDITOR || DEVELOPMENT_BUILD + void OnGUI() + { + var debug = new StringBuilder("FMOD System\n"); + + FMOD.Memory.GetStats(out int currentAlloc, out int maxAlloc); + debug.AppendFormat("MEMORY: cur = {0}MB, max = {1}MB\n", currentAlloc >> 20, maxAlloc >> 20); + + fmodSystem.getChannelsPlaying(out int channels, out int realChannels); + debug.AppendFormat("CHANNELS: real = {0}, total = {1}\n", realChannels, channels); + + GUI.Box(new Rect(0, 300, 250, 60), debug.ToString()); + } +#endif }