'Call a Method On Hot Reload

I am making a game using Visual Studio 2022 and C# and I was wondering if it was possible to trigger some code when you hot reload your app (whilst it's running).

I basically have 2 methods called UnloadLevel and LoadLevel that I would like to execute on Hot Reload.

I am building a game and to make levels I have the LoadLevel method that puts all the elements (the platforms, entities etc) from this LevelData static class into the game scene. The UnloadLevel function does the opposite. In order to build the levels fast without making an entire fledged out LevelEditor which would be long and tidious to make, I thought using the Hot Reload function of visual studio 2022 to change the LevelData, hot reload, and automatically see the changes in my level scene without having to unload and reload manually.

Thanks in Advance



Solution 1:[1]

I believe MetadataUpdateHandlerAttribute is what you're looking for (originally found here).

Example:

[assembly: System.Reflection.Metadata.MetadataUpdateHandler(typeof(HotReloadManager))]

public static class HotReloadManager
{
    public static void ClearCache(Type[]? updatedTypes)
    {
        Console.WriteLine("HotReloadManager.ClearCache");
    }

    public static void UpdateApplication(Type[]? updatedTypes)
    {
        Console.WriteLine("HotReloadManager.UpdateApplication");
    }
}

The setup is a bit weird, involving magic-name methods instead of eg an interface. Also, note that the attribute applies to the assembly, not the class.

You might see references to ASP.NET while googling this, but don't worry it works fine in eg a console app (using it for a game engine myself).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 benblo