Getting Type and Value of SerializedProperty

There some code samples on internet. None of work MeshFilter’s m_Mesh field. When I read MeshFilter with iterator I get a serializedProperty with name m_Mesh, but there is no m_Mesh field in MeshFilter. So I cannot use reflection to get fieldInfo for m_Mesh. How can I get type and value?

What is the property path of m_Mesh? Is it nested inside an existing property?

Yes, you can not get access to m_Mesh because it’s not a field in the managed MeshFilter class but in the native C++ class. Unity’s serialization system primarily works on the native C++ side. MeshFilter is a built-in component and the field in question is part of the native code. On the managed side you can only access it through the mesh / sharedMesh property of that class. Those properties actually call native methods.

Almost all built-in components and classes are just empty wrapper classes for native classes. This is true for Transform, GameObject, Collider, Mesh, Material, etc. The serialization system also support serializing managed fields in MonoBehaviour or ScriptableObject classes. This is a special feature of the serializer but from Unity’s perspective actually an exception. From your point of view those managed fields are probably those you care about the most.

As I said pretty much all UnityEngine.Object derived types are just empty hulls which contain no fields except the internal instance id and the cached PTR to the native class. All the fancy properties you get in those classes actually call methods on the native class in the engine core. Many people seem to forget that Unity is written in C++. C# is “just” a scripting layer.

So in short: You can not use reflection with the property path since the property is not a managed property. For built-in classes you would need to use the corresponding properties instead. Keep in mind that a MeshFilter could have an individual mesh instance or a shared instance. Especially from editor code you can not use the “mesh” property as it would instantiate a temporary mesh on the fly which is not allowed in the editor. I think Unity used to throw a warning / error when you try. So in the editor you should use the sharedMesh / sharedMaterial(s) property

ps: The MeshFilter class literally just looks like this.

4 Likes

@Bunny83 Thanks for detailed explanation. I assumed there is always reflection pair of an serialized property. Now I know it is not true. How can I check this from a serialized property fields? I attached serialized property fields for Mesh and Int fields. Can I use type field and starting with “PPtr<” ?

Mesh;

Int;