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?
//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 *== "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*, 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?
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*); *
@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
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?
– mhoferFigured it out! it's type.GetEnumerableType();
– mhoferThis is pretty similar to the code that Unity uses internally to get the type.
– rockwalrus