- Home /
Help with GetType().GetField().GetValue()
Hello People!
I've find a solution to read variable values from a string, but my code does not work... its have error all time, what I'm missing? or What is wrong?
this.GetType(int).GetField("Resource"+LoadedResource).GetValue();
LoadedREsource is a string name, and when i use
Debug.Log("Resource"+LoadedResource)
Is exactly what i need, but this is not the problem, the line remains with the red mark of "incorrect".. Anny help?
Thanks guys!
Answer by tormentoarmagedoom · Apr 06, 2018 at 11:41 AM
Good day craftingtycoon !
I think you are missing the object in the GetValue. You need to say what object contains the variable. In this case i supose is "this". So you need this:
this.GetType(int).GetField("Resource"+LoadedResource).GetValue(this);
Aaaand in case you want to SetValue(), you will need to write the GetValue sentence inside the SetValue() like this:
this.GetType(int).GetField("Resource"+LoadedResource).SetValue(this.GetType(int).GetField("Resource"+LoadedResource).GetValue(this), NewValue);
If hellped accept the answer :D
Wow thanks for quick response, i dont have the red mark now, i supose it will work, we will see :D
Thank you!
Uhm your second code snippet doesn't make much sense. SetValue expects the actual object just like GetValue but in addition the new value to which the field should be set to. Passing the value as object makes no sense. GetValue as well as SetValue need the same object reference. Specifically an object of the type from which you got the FieldInfo from.
So inside the same class you would do
var fi = this.GetType().GetField("Resource"+LoadedResource);
var value = fi.GetValue(this);
fi.SetValue(this, newValue);
Though i would generally not recommend such an approach. The class design is flawed if you need to use reflection. It's better to represent a resource with a simple serializable class and use a dictionary to lookup a specific resource. It's faster and more flexible.
Appart from that answer being wrong, the whole concept is plainly counterproductive, regarding the fact you are working inside the class the field is, using reflection to manipulate them, unless you generate code on runtime. this and reflection shouldn't be used together and as a rule of thumb reflection should be avoided on runtime.
GetType() has no overload to support the GetType(int) which would again make no sense. Cheers.