🏒
Puck
  • Welcome!
  • GETTING STARTED
    • Development environment setup
    • Using the Puck API
    • Testing your mod
    • Development optimizations
  • PUBLISHING
    • SteamWorkshopUploader
    • Publishing to the Steam Workshop
  • Puck API
    • Singletons
    • Harmony
    • Referencing the source
Powered by GitBook
On this page
  1. Puck API

Harmony

As quoted from the Harmony GitHub page:

Harmony gives you an elegant and high level way to alter the functionality in applications written in C#.

Harmony is shipped with Puck and no additional dependencies are needed from the mod side in order to use it.

Let's imagine we want to create a mod that prevents spectators from using the chat. This can be easily achieved with a simple prefix patch:

public class Class1 : IPuckMod
{
    // Create a new instance of Harmony
    static readonly Harmony harmony = new Harmony("GAFURIX.MyPuckMod");

    // Let's patch the Server_ProcessPlayerChatMessage function within UIChat
    [HarmonyPatch(typeof(UIChat), "Server_ProcessPlayerChatMessage")]
    public class ProcessPlayerChatMessagePatch
    {
        // Prefix allows us to prevent original code from executing
        [HarmonyPrefix]
        public static bool Prefix(
            Player player,
            string message,
            ulong clientId,
            bool useTeamChat,
            bool isMuted
        )
        {
            if (
                player.Team.Value == PlayerTeam.Spectator
                || player.Team.Value == PlayerTeam.None
            )
            {
                // Returning false prevents original function's code from executing
                return false;
            }

            // Return true to continues executing Server_ProcessPlayerChatMessage
            return true;
        }
    }

    public bool OnEnable()
    {
        try
        {
            // Patched all functions we have defined to be patched
            harmony.PatchAll();
        }
        catch (Exception e)
        {
            Debug.LogError($"Harmony patch failed: {e.Message}");

            return false;
        }

        return true;
    }

    public bool OnDisable()
    {
        try
        {
            // Reverts our patches, essentially returning the game to a vanilla state
            harmony.UnpatchSelf();
        }
        catch (Exception e)
        {
            Debug.LogError($"Harmony unpatch failed: {e.Message}");

            return false;
        }

        return true;
    }
}

Patching is powerful, though Harmony offers a lot more than just patching, which is better covered in the original Harmony 2 documentation.

PreviousSingletonsNextReferencing the source

Last updated 8 days ago