I want to add value to a value I got through reflection. The += does not work and SetValue does not fit my needs. *
- Instance.Field does exist but this would not be good for my script(For reasons).
Here is my class:
public class OreMine : MonoBehaviour
{
[SerializeField] string VariableName;
void OnCollisionEnter2D(Collision2D col)
{
if(col.gameObject.tag == "Player")
{
var Value = typeof(Inventory).GetField(VariableName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);
Destroy(gameObject);
}
}
}
The problem is that I could not do this:
Value += 1
And this would not suit my needs:
public class OreMine : MonoBehaviour
{
valueField.SetValue(null, SomeInteger);
}
And in Microsoft documentation the AddValue seems like it's only for strings.
Value += 1is simplyValue = Value + 1. If you're using reflection, you'll need aGetValue, a cast to the correct type fromobject, an increment, and aSetValue(which will have an implicit cast/box back toobject). This ahs nothing to do withAddValue, which is a serialization concept.Reflection is probably the worst way of approaching this problem, though. I might see whether adding an
ISomethinginterface with avoid Increment()or whatever method, so I can just go:and have individual types worry about what that means.