How can I add value to a reflected variable?

41 Views Asked by At

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.

https://learn.microsoft.com/en-us/dotnet/api/system.runtime.serialization.serializationinfo.addvalue?view=net-8.0

1

There are 1 best solutions below

1
Marc Gravell On

Value += 1 is simply Value = Value + 1. If you're using reflection, you'll need a GetValue, a cast to the correct type from object, an increment, and a SetValue (which will have an implicit cast/box back to object). This ahs nothing to do with AddValue, which is a serialization concept.

Reflection is probably the worst way of approaching this problem, though. I might see whether adding an ISomething interface with a void Increment() or whatever method, so I can just go:

if (obj is ISomething typed)
    typed.Increment();

and have individual types worry about what that means.