Files
ADOFAIRenderer/Util/BundleLoader.cs
T
2026-10-15 16:17:13 +09:00

60 lines
2.6 KiB
C#

using System;
using System.Reflection;
using System.Resources;
using MelonLoader;
using UnityEngine;
namespace ADOFAIRenderer.Util;
/// <summary>
/// Loads the Unity asset bundles (fonts, shaders) embedded in the mod DLL as manifest resources. One bundle set is
/// embedded per platform (Bundle/Win64, Bundle/OSX, Bundle/Linux).
/// Main thread (AssetBundle loading).
/// </summary>
internal static class BundleLoader
{
/// <summary>Resource folder of the running platform: "Win64" on Windows, "OSX" on macOS, "Linux" otherwise.</summary>
private static readonly string BundlePlatform;
/// <summary>The mod assembly that contains the bundle resources.</summary>
private static readonly Assembly? ExecutingAssembly;
static BundleLoader()
{
BundlePlatform = Application.platform switch
{
RuntimePlatform.WindowsPlayer => "Win64",
RuntimePlatform.OSXPlayer => "OSX",
_ => "Linux"
};
ExecutingAssembly = Assembly.GetExecutingAssembly();
}
/// <summary>
/// Loads the bundle stored as manifest resource "ADOFAIRenderer.Bundle.&lt;platform&gt;.&lt;resourcePath&gt;" with
/// AssetBundle.LoadFromStream. The resource stream is disposed when this method returns. The caller owns the returned
/// bundle.
/// Reference: https://docs.unity3d.com/ScriptReference/AssetBundle.LoadFromStream.html
/// </summary>
/// <param name="resourcePath">Bundle name inside the platform folder, for example "fonts" or "shaders".</param>
/// <returns>The loaded bundle, or null when Unity fails to load it.</returns>
/// <exception cref="MissingManifestResourceException">The resource is not embedded in the DLL.</exception>
/// <exception cref="InvalidOperationException">The executing assembly is not available.</exception>
public static AssetBundle GetBundle(string resourcePath)
{
if (ExecutingAssembly != null)
{
var bundlePath = $"ADOFAIRenderer.Bundle.{BundlePlatform}.{resourcePath}";
using var resourceStream = ExecutingAssembly.GetManifestResourceStream(bundlePath);
if (resourceStream != null)
{
return AssetBundle.LoadFromStream(resourceStream);
}
Melon<RenderMod>.Logger.Error($"Could not find bundle resource in DLL.\n{bundlePath}");
throw new MissingManifestResourceException("Could not find bundle resource in DLL.");
}
Melon<RenderMod>.Logger.Error("Executing assembly has not been set properly.");
throw new InvalidOperationException("ExecutingAssembly has not been set.");
}
}