SetValueDirect throws a not implemented error and when I am trying to use SetValue the variable is boxed so I can’t actually change it, I can’t seem to find alternative to this. I just want to find a variable by name and then change the value of it. Thanks.
I am getting the “StatPoints” string from a txt file and trying to change the variable with the corresponding name.
public class Main : MonoBehaviour{
int StatPoints = 20;
public void Save (bool Saving)
{
var data2 = new Main();
FieldInfo field = data2.GetType().GetField("StatPoints", BindingFlags.Instance | BindingFlags.NonPublic);
field.SetValue(data2, 10);
}
}
Ok, based on your latest comment i think I’m ready to answer your question. In your case the issue has nothing to do with boxing but that “Main” is actually a MonoBehaviour. You can not create a MonoBehaviour with new. MonoBehaviours are components which can only be “created” with AddComponent. However in your case you most likely want to set the field of the MonoBehaviour instance you’re currently on since your Save method is an instance method you must already have a valid instance on some GameObject.
So what you want to do is this:
public void Save (bool Saving)
{
FieldInfo field = this.GetType().GetField("StatPoints", BindingFlags.Instance | BindingFlags.NonPublic);
field.SetValue(this, 10);
}