Hooks that only get patched & unpatched per plugin.
Automatic Way
In RustPluginor CarbonPlugin, Carbon 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.
using Oxide.Core.Plugins;
[AutoPatch]
[HarmonyPatch(...)]
public class MyPatch { ... }
using System;
using HarmonyLib;
using Oxide.Core.Plugins;
namespace Carbon.Plugins;
[Info("Collaborate", "Carbon Community", "1.0.0")]
public class Collaborate : CarbonPlugin
{
#region Patches
[AutoPatch]
[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
}
While this is entirely Oxide-compatible, we've expanded on the use of the [AutoPatch] attribute with the following options:
using System;
using HarmonyLib;
using Oxide.Core.Plugins;
namespace Carbon.Plugins;
[Info("Collaborate", "Carbon Community", "1.0.0")]
public class Collaborate : CarbonPlugin
{
#region Patches
public void OnPatchComplete()
{
// Run special code here only if the patch is successful
}
[AutoPatch(
IsRequired = true, // If the patch fails, automatically unload the plugin
Order = AutoPatchAttribute.Orders.AfterOnServerInitialized, // Specify at what time on the plugin's initialization should the patch apply
PatchSuccessCallback = nameof(OnPatchComplete))]
[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
}