BepInEx / HarmonyX

Harmony built on top of MonoMod.RuntimeDetours with additional features
MIT License
329 stars 42 forks source link

How do I call a private function within a postpatch #109

Closed grossbacher closed 3 months ago

grossbacher commented 3 months ago

I've searched for a pretty long time and I can't find anything on calling a private function. I'm an ultrakill modder (one of the few) and I have only found 1 resource that I couldn't understand on how to do it. Is there a simple way of doing this?

Here's the function that I'm trying to call private void Shoot(int shotType = 1)

Better yet, is there a good tutorial on BepinEX modding? If not, I might just make one myself.

ManlyMarco commented 3 months ago

This is a general C# question, not a Harmony/BepInEx question. See https://learn.microsoft.com/en-us/dotnet/framework/reflection-and-codedom/reflection and https://stackoverflow.com/questions/135443/how-do-i-use-reflection-to-invoke-a-private-method

Official BepInEx readme is at https://docs.bepinex.dev

grossbacher commented 3 months ago

I saw this when I 1st looked the problem up, have absolutely NO idea how to use it. What would I most likely replace this with? Would it be the script name I patched? (Example: [HarmonyPatch(typeof(Revolver), "Update")] (Putting Revolver instead of THIS is my best guess, but doesn't work) This is probably very important to learn, do you know?

grossbacher commented 3 months ago

Original code for reference: MethodInfo dynMethod = this.GetType().GetMethod("Draw_" + itemType, BindingFlags.NonPublic | BindingFlags.Instance); dynMethod.Invoke(this, new object[] { methodParams });

grossbacher commented 3 months ago

I probably should have mentioned: The function is inside of the Revolver script where I'm patching Update.

Normally, when I make games with unity, you can call private functions as long as they're defined in the same script they're called in. I read through the reflection help guide, and everyone's saying to avoid reflections at all costs. It can't be this hard, right? Is there any other way, like editing the function to be public and hoping it doesn't break anything?

PhantomGamers commented 3 months ago

this would be __instance

see https://github.com/BepInEx/HarmonyX/wiki/Patch-parameters

grossbacher commented 3 months ago

I'll ask the lethal company discord, they're always helpful, but this puts me a step in the right direction! Thank you!

grossbacher commented 3 months ago

this would be __instance

see https://github.com/BepInEx/HarmonyX/wiki/Patch-parameters

Wait actually I have another question. How would I get Instance? Do I have to ref Script instance or is it automatic?

grossbacher commented 3 months ago

Nevermind, I figured it out! The code doesn't work, but I know how to do it!