Let's assume I have a class ClassWithMember
class ClassWithMember
{
int myIntMember = 10;
}
How do I get the default value 10 of the myIntMember member by System.Type?
I'm currently struggling around with reflections by all I retreive is the default value of int (0) not the classes default member (10)..
You can try something like this:
The trick here is to instantiate an instance.
You can still use Activator.CreateInstance to create a MonoBehaviour/ScriptableObject and check its values, if it's simply for the sake of checking the default Values. Make sure to use DestroyImmediate afterwards ;-)
If you're in control of the code for ClassWithMember, you could take a completely different approach to this by using the
[DefaultValue]
attribute fromSystem.ComponentModel
. Basically, what you'd do is write something like this:And then have a function like this somewhere, perhaps in a base class:
So now, you have a situation where you can easily retrieve the default values using Reflection.
Keep in mind that this is going to be quite a lot slower due to the Reflection requirement, so if this code gets instantiated a lot, you'll probably want to find a different approach. Also, it won't work with non-value types, due to a limitation with the .NET Framework's attribute support.
Try creating an instance an retreive the value with reflection.