- Home /
Get field type of SerializedProperty
I'm in a situation where I require to know the type that a SerializedProperty is storing. I know the serialized property is of SerializedPropertyType.ObjectReference, but that's all I can work out.
What I need is the actual type (GameObject, Transform, TextAsset, Camera, etc.). Is there any way of doing this?
Thanks
Answer by $$anonymous$$ · Mar 21, 2015 at 05:49 AM
I resorted to using reflection, although I had hoped I wouldn't need to. I'd still like to know any solutions that are more straightforward.
string[] parts = property.propertyPath.Split('.');
Type currentType = target.GetType();
for (int i = 0; i < parts.Length; i++)
{
Debug.Log(currentType + " " + parts[i]);
currentType = currentType.GetField(parts[i], BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.FlattenHierarchy | BindingFlags.Instance).FieldType;
}
Type targetType = currentType;
Essentially, using the path of the property, I find the field with reflection to get the type.
This won't work with properties inside array, since path is like someName.Array.data[4].someName... Check my answer for a modified solution
Answer by scanzy · Apr 19, 2017 at 05:03 PM
This works also for properties inside arrays
//gets parent type info
string[] slices = prop.propertyPath.Split('.');
System.Type type = prop.serializedObject.targetObject.GetType();
for(int i = 0; i < slices.Length; i++)
if (slices[i] == "Array")
{
i++; //skips "data[x]"
type = type.GetElementType(); //gets info on array elements
}
//gets info on field and its type
else type = type.GetField(slices[i], BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.FlattenHierarchy | BindingFlags.Instance).FieldType;
//type is now the type of the property
type.GetElementType() only returns something when the element is not null. Do you happen to know how I can get the type that fits in there?
This is pretty similar to the code that Unity uses internally to get the type.
Answer by llamagod · Sep 25, 2016 at 01:45 PM
@Narmdo Sorry for resurrecting an old thread. If you want the object reference type of the property you can use regex and Type.GetType, or if you're in a PropertyDrawer you can just use the PropertyDrawer.field field. Here are two methods from my EditorExtensions library.
public static string GetPropertyType(SerializedProperty property)
{
var type = property.type;
var match = Regex.Match(type, @"PPtr<\$(.*?)>");
if (match.Success)
type = match.Groups[1].Value;
return type;
}
public static Type GetPropertyObjectType(SerializedProperty property)
{
return typeof(UnityEngine.Object).Assembly.GetType("UnityEngine." + GetPropertyType(property));
}
This won't work for user defined types, unless they belong to UnityEngine namespace
Your answer
Follow this Question
Related Questions
What does a [SomeName] Above A Variable Mean? 2 Answers
ObjectField functions ignoring parameter 1 Answer
Servers connection differences/uses 1 Answer
Type in bug in editor 1 Answer