Page cover image

Plugin Patches / Hooks

Hooks that only get patched & unpatched per plugin.

Automatic Way

In CarbonPlugin, Carbon already handles all the logic for patching / unpatching your instructions, making it easier so all you need to focus on is the actual implementation of your plugin.

You need to add this line which lets Carbon know that it should automatically handle everything for you.

public override bool AutoPatch => true;
using System;
using HarmonyLib;

namespace Carbon.Plugins;

[Info("Collaborate", "Carbon Community", "1.0.0")]
public class Collaborate : CarbonPlugin
{
    public override bool AutoPatch => true;

    #region Patches

    [HarmonyPatch(typeof(BasePlayer), "CanSuicide", new Type[] { })]
    public class Patch_1
    {
       public static bool Prefix(BasePlayer __instance, ref bool __result)
       {
          Logger.Log("Works!");
          __result = false;
          return false;
       }
    }

    #endregion
}

Manual Way

There are 2 ways you can create your own hooks, which are fairly similar in execution.

Carbon automatically includes the Harmony library into the compiler, which means it's not necessary to do // Reference: 0Harmony.

Here's an example to how this works when you manually add patches to your plugin:

using System;
using HarmonyLib;

namespace Carbon.Plugins;

[Info("Collaborate", "Carbon Community", "1.0.0")]
public class Collaborate : CarbonPlugin
{
    public Harmony _PATCH;
    public const string DOMAIN = "com.carbon.mypatch";

    private void Init()
    {
       _PATCH = new Harmony(DOMAIN);
       _PATCH.PatchAll(Type.Assembly);

       Puts("Patched.");
    }

    private void Unload()
    {
       _PATCH.UnpatchAll(DOMAIN);

       Puts("Unpatched.");
    }

    #region Patches

    [HarmonyPatch(typeof(BasePlayer), "CanSuicide", new Type[] { })]
    public class Patch_1
    {
       public static bool Prefix(BasePlayer __instance, ref bool __result)
       {
          Logger.Log("Works!");
          __result = false;
          
          // Returning false will prohibit the original code from executing
          // Only applies to Prefixes
          return false;
       }
    }

    #endregion
}

Last updated