Repository navigation
Before Hook
This page is about
@Beforehooks specifically. You should make sure to read the general page about Hooks before it.
The @Before hook lets you run code at the start of a method, right before the original code.
There are three general purposes for @Before patches:
- Calling your own code right at the beginning of a method
- Modifying an input argument
- Skipping the original method's code entirely
Before hooks require the BeforeContext type for their patch handler's context parameter.
context.setArg() is available for every hook context, but it is most useful in before patches. For example, below is a patch that affects every campaign fleet. It retrieves the original amount parameter. If you are unaware, amount is essentially what other game engines may classify as delta time. It's the time that has passed since the method was last called. This value allows everything time-related to perform framerate-independent calculations.
This patch retrieves that value and reduces it by 10x for every non-player fleet with context.setArg, causing every other fleet to move in slow motion.
@Patch(target = @ClassMatch(subtype = CampaignFleetAPI.class))
public class BeforeExample {
@Before(target = @MethodMatch(methodName = "advance", parameterCount = 1))
public static void beforeAdvance(BeforeContext context) {
CampaignFleetAPI fleet = (CampaignFleetAPI) context.getSelf();
float amount = (float) context.getArg(0);
if (!fleet.isPlayerFleet()) {
context.setArg(0, amount * 0.1f);
}
}
}Before patches can use context.skipOriginal to skip the original method body. Note that this is one of the most destructive operations that can be done and should be used carefully. Whenever a method returns something other than void, you also need to provide a replacement return value. If it does not have a return value, you just need to provide null.
@After patches will still run on methods that were skipped, and can use context.isSkipOriginal() to check if a prior patch skipped the original method body.
The example below skips the code in doGoSlow, disabling the slowing behavior from the Go Dark ability or holding S. In a more realistic example, you could skip the original code so that you can replace it with your own logic instead.
@Patch(target = @ClassMatch(subtype = CampaignFleetAPI.class))
public class BeforeExample {
@Before(target = @MethodMatch(methodName = "doGoSlow"))
public static void beforeDoGoSlow(BeforeContext context) {
context.skipOriginal(null);
}
}- Home
- Introduction to Patchlib
- Patch Types
- Working with obfuscated code
- Example Patches
- Other utilities
- Patching with Kotlin
- Developer Documentation