Potential improvement to serialisation of materials with custom properties
Posted: Mon Jul 18, 2022 5:47 pm
Currently the serialisation of
Looking at the API documentation, it appears that while the names and types of properties aren't available via the
UnityEngine.Material
calls Material.HasProperty
with a bunch of predefined property names, and then when it does indeed have the given property, calls the relevant Material.Get*
method for that name's associated type. This isn't particularly flexible as materials with custom shaders can use custom property names and give each property a custom type.Looking at the API documentation, it appears that while the names and types of properties aren't available via the
Material
interface, they are available via the Shader
interface, so it looks like it would be viable to get the material's shader and iterate over its properties, calling Shader.GetPropertyName
and Shader.GetPropertyType
Shader.GetPropertyCount
times, using a switch
to serialise the material's value for the property as the correct type. Similarly, when deserialising, Shader.GetPropertyIndex
could be used to get the index required to call Shader.GetPropertyType
again to extract the right type from the JSON data.