81 lines
3.1 KiB
C#
81 lines
3.1 KiB
C#
using System;
|
||
using BrewMonster;
|
||
using UnityEngine;
|
||
using UnityEngine.AddressableAssets;
|
||
using UnityEngine.ResourceManagement.ResourceLocations;
|
||
|
||
namespace BrewMonster.Scripts
|
||
{
|
||
/// <summary>
|
||
/// Runtime rewrite of bundle/catalog URLs via <see cref="Addressables.InternalIdTransformFunc"/>
|
||
/// (e.g. swap CDN host or path prefix). Must run before the first successful remote load — ideally before
|
||
/// <see cref="Addressables.InitializeAsync"/> if all remote ids should be rewritten.
|
||
/// </summary>
|
||
public static class AddressablesRuntimeUrlRewriter
|
||
{
|
||
static Func<IResourceLocation, string> s_previousTransform;
|
||
static string s_fromPrefix;
|
||
static string s_toPrefix;
|
||
|
||
/// <summary>
|
||
/// When true, the installed rewriter calls the previous <see cref="Addressables.InternalIdTransformFunc"/> first.
|
||
/// </summary>
|
||
public static bool ChainPreviousTransform { get; set; } = true;
|
||
|
||
/// <summary>
|
||
/// Replaces the start of each location’s <see cref="IResourceLocation.InternalId"/> when it begins with
|
||
/// <paramref name="fromPrefix"/> (e.g. build-time profile URL) by <paramref name="toPrefix"/> (runtime CDN).
|
||
/// </summary>
|
||
public static void InstallPrefixRewrite(string fromPrefix, string toPrefix)
|
||
{
|
||
if (string.IsNullOrEmpty(fromPrefix))
|
||
{
|
||
BMLogger.LogError("AddressablesRuntimeUrlRewriter: fromPrefix is null or empty.");
|
||
return;
|
||
}
|
||
|
||
s_fromPrefix = fromPrefix;
|
||
s_toPrefix = toPrefix ?? string.Empty;
|
||
|
||
if (ChainPreviousTransform)
|
||
s_previousTransform = Addressables.InternalIdTransformFunc;
|
||
|
||
Addressables.InternalIdTransformFunc = Transform;
|
||
BMLogger.Log($"AddressablesRuntimeUrlRewriter: Installed prefix rewrite (from length={fromPrefix.Length}, to length={s_toPrefix.Length}).");
|
||
}
|
||
|
||
/// <summary>
|
||
/// Removes this package’s rewrite and restores the delegate that was present at install time (if any).
|
||
/// </summary>
|
||
public static void ClearInstalledRewrite()
|
||
{
|
||
if (Addressables.InternalIdTransformFunc == Transform)
|
||
{
|
||
Addressables.InternalIdTransformFunc = s_previousTransform;
|
||
s_previousTransform = null;
|
||
s_fromPrefix = null;
|
||
s_toPrefix = null;
|
||
BMLogger.Log("AddressablesRuntimeUrlRewriter: Cleared installed rewrite.");
|
||
}
|
||
}
|
||
|
||
static string Transform(IResourceLocation location)
|
||
{
|
||
string id = location != null ? location.InternalId : null;
|
||
if (string.IsNullOrEmpty(id))
|
||
return id;
|
||
|
||
if (ChainPreviousTransform && s_previousTransform != null)
|
||
id = s_previousTransform(location);
|
||
|
||
if (!string.IsNullOrEmpty(s_fromPrefix) &&
|
||
id.StartsWith(s_fromPrefix, StringComparison.OrdinalIgnoreCase))
|
||
{
|
||
return s_toPrefix + id.Substring(s_fromPrefix.Length);
|
||
}
|
||
|
||
return id;
|
||
}
|
||
}
|
||
}
|