Skip to content

How to reload mod at runtime

newman55 edited this page Sep 6, 2024 · 1 revision

This feature is added in version 0.14.1.

You can reload the assembly without restarting.

Add the following command to Post-build event so that the compiled file is copied automatically.

start XCOPY /Y /R "$(TargetPath)" "D:\Games\YourGame\Mods\$(ProjectName)\$(ProjectName).dll*"

In the source code of your mod, you need to specify that the mod can be reloaded. Add EnableReloading attribute to the main class and set Unload function to modEntry.

[EnableReloading]
modEntry.OnUnload = Unload;

In mod options should appear Reload button.

Reload button

You only need to create the Unload function and remove all patches and objects of the old assembly. In fact, the old assembly cannot be unloaded, but we can stop all of its work. I'll give you some examples to make it clearer.

using UnityEngine;
using HarmonyLib;
using UnityModManagerNet;

namespace ExampleMod
{
#if DEBUG
    [EnableReloading]
#endif
    static class Main
    {
        static bool Load(UnityModManager.ModEntry modEntry)
        {
            var harmony = new Harmony(modEntry.Info.Id);
            harmony.PatchAll(Assembly.GetExecutingAssembly());

            modEntry.OnUnload = Unload;

            return true;
        }

        static bool Unload(UnityModManager.ModEntry modEntry)
        {
            var harmony = new Harmony(modEntry.Info.Id);
            harmony.UnpatchAll(modEntry.Info.Id);
			
            // If you have created any dependent objects, they also need to be deleted.
            
            return true;
        }
    }
}
Clone this wiki locally