I got a very specific case and I read tons of questions on StackOverflow about setting and getting private fields and properties of classes but they all do not seem to work.
I am modding a Unity game by injecting code with Harmony ( a library to inject code at runtime). I successfully changed a lot of things but as soon as values are private, I hit a wall since I cannot access nor change the values.
When inspecting the code with dnSpy: So there is the public class World {} which contains the field public static World inst as well as two private fields private int GridWidth and private int GridHeight. It also contains the properties GridWidth and Gridheight, both public but only with a Getter. It contains further fields which do not matter here. World.inst gets set in the private void Awake() method, a specific Unity method.
In short:
public class World : MonoBehaviour
{
public static World inst;
private void Awake()
{
World.inst = this;
this.gridWidth = 55;
this.gridHeight = 55;
}
private int GridWidth;
private int GridHeight;
public int GridWidth
{
get
{
return this.gridWidth;
}
}
public int GridHeight
{
get
{
return this.gridHeight;
}
}
}
Now I tried to change the values of GridWidth and GridHeight externally but failed. I cannot change this part of the code.
In dnSpy, the two fields are referrenced ( when hovering over the fields) as World.GridWidth and World.GridHeight but they are clearly set as World.inst.GridWidth and GridHeight.
My current code is
var WorldField = typeof(World).GetField("GridWidth", BindingFlags.Instance | BindingFlags.NonPublic);
WorldField.SetValue(World.inst, 100);
But this does not work. I haven't really worked with Reflection yet and it might be that I am making a really obvious mistake, if so, I am very sorry.
I am very confused and any help and indepth Explanation is very appreciated.
Aucun commentaire:
Enregistrer un commentaire