Use Internal Class in C# Harmony Patch

4.1k views Asked by At

I'm pretty new to c#, and I'm using Harmony patches to make a mod for a video game. The method I'm trying to patch is a private method which takes an internal class instance as a parameter. I've been able to use reflection to handle private methods in a few other patches, but when I try to add the internal parameter, I get a build error saying the class is inaccessible due to it's protection level.

I was trying to use the solution from this question, but I think I'm having some scope issues. Right now, I have something like

using System;
...
using System.Reflection;
using HarmonyLib;
using namespacesFromGame;  // Including namespace where the internal is declared
... 

namespace MyMod
{
    [HarmonyPatch(typeof(GameClass))]
    class MyPatch
    {
        Type MyInternal = typeof(GameClass).Assembly.GetType("GameInternal");
        public static bool MethodPatch(GameClass__instance,..., MyInternal myInternal, ...)
        {
             ...
        }
    }
}

When I try to do this, it tells me The type or namespace name 'MyInternal' cannot be found.

Where should I be putting my MyInternal declaration so it can be used as a parameter to MethodPatch, and so I will also be able to use the myInternal instance in the patch?

1

There are 1 answers

0
Valentin Arthur Thomas On

In C# you cannot declare the type of a property with another variable. I see two solutions to this problem.

You can either do this :

using System;
...
using HarmonyLib;
using namespacesFromGame;  // Including namespace where the internal is 

namespace MyMod
{
    [HarmonyPatch(typeof(GameClass))]
    class MyPatch
    {
        public static bool MethodPatch(GameClass __instance,..., object myInternal, ...)
        {
             ...
             // do reflexion to access the method, the field and prop the object
        }
    }
}

This should work; but if you are new to C# the reflection may not necessarily be the easiest thing to do and it can quickly make your code unreadable.

Or do this :

You can publicise (make public) the dll you want to use. If you do this, you will have access to all classes, methods and ect... By doing this you will only have to use the desired type. But, you will have to compile your code in unstable.

For publicise, i found two github repo :

It will require republishing the assembly each time there is an update if your mod is outdated.

I also create modes on unity games. This is the solution I use and some FrameWork for modding uses to. I don't know if there are performance impacts of using unstable code and calling private methods. I advise you this solution, you would get cleaner code and you will have access to code more easily. But that is my personal opinion.