0

I'm trying to make a function that gets a SerializedProperty via a string path and then it converts it into a generic type and returns that. I have tried many solutions and they either gives an exception of null refrence or invalid cast. I simply have no clue on what to do. So could someone be kind and help me? thanks! btw this is the function so far:

T GetObjectProperty<T>(string propertyPath)
{
    SerializedProperty property = serializedObject.FindProperty(propertyPath);



}
Techno Man
  • 3
  • 1
  • 6
  • In your example you are not returning anything. What exactly do you want to do? / What is your goal with that? – derHugo May 22 '18 at 13:45
  • The goal of this function is to first find the property via the propertyPath (there is no otherway to do this part) and then get the T value from the property and return that – Techno Man May 25 '18 at 14:25

1 Answers1

0

It's not that simple unfortunately: Unity - SerializedProperty has a lot of different properties like e.g. intValue, floatValue, boolValue.

If you are after an object reference as the naming of your function sounds to me you are probably after the objectReferenceValue.


Otherwise you somehow have to define exactly which value you want to access; I did this once by passing the wanted type as second parameter:

object GetValueByName(Type type, string name)
{
    SerializedProperty property = serializedObject.FindProperty(name);

    if(type == typeof(int))
    {
        return property.intValue;
    } 
    else if(type == typeof(float))
    {
        return property.floatValue;
    }
    //... and so on

}

Than whenever I used the method I only had to parse like e.g.

int someValue = (int)GetValueByName(typeof(int), "XY");

If you want to stick to the genric method instead of returning object and parse you can as well check for typeof(T) instead of pssing it as parameter:

T GetValueByName<T>(string name)
{
    SerializedProperty property = serializedObject.FindProperty(name);

    Type type = typeof(T);
    if(type == typeof(int))
    {
        return property.intValue;
    } 
    else if(type == typeof(float))
    {
        return property.floatValue;
    }
    //... and so on

}

hope this helps you


(ps: if you prefere to use switch-case instead of the multiple if-else refer to this answer)

derHugo
  • 83,094
  • 9
  • 75
  • 115