废话不多说,直接上代码
using System.Reflection; using HarmonyLib; using UnityEngine; using estudio.Common; namespace estudio { public class H_BackgroundMenuClipRepair { //表示要进行补丁的目标成员 [HarmonyPatch(typeof(BackgroundMusicMono), "Start")] public class BackgroundMusicMono_Start_Patch { //此属性为AudioClip的加载路径 private static string MyPath { get { //Assembly.GetExecutingAssembly()可以获取当前运行的程序集,通过调用Location属性可以获取到它的位置 string dllInThat = Assembly.GetExecutingAssembly().Location; //拿到DLL路径后进行路径字符串截取,不懂得可以去查看相关API,大概作用就是截取路径字符串让它不包含DLL名称及扩展名(也就是Mod根路径) string rootLocation = dllInThat.Substring(0, dllInThat.LastIndexOf("xxx.dll") - 1); //属性的返回值就是Mod根路径加上自定义Clip资源存放路径,注意要写全和你在XML调用unity模型一样! return $"#{rootLocation}/Bundle/xxx.unity3d?xxx"; } } //Prefix表示在目标成员首行前插入代码/补丁 [HarmonyPrefix] //由于我们不需要进行拦截,所以即使该函数被HarmonyPrefix特性标记我们也不需要它有任何返回值 public static void AddPrefix() { //通过DataLoader类里面的LoadAsset静态泛型方法调用自定义资源,泛型类型为AudioClip,参数为资源路径 AudioClip clip = DataLoader.LoadAsset<AudioClip>(MyPath); //null值处理,我就不再过多强调(这里做了一个早期返回处理) if (clip == null) { Debug.LogWarning("Cannot load given audio clip! Ignoring..."); return; } //如果资源不为null,就不会被return掉。然后将加载的自定义背景音乐Clip赋值给原版DLL进行覆盖,让他加载我们的Clip GameManager.Instance.BackgroundMusicClip = clip; } } } }