1
\$\begingroup\$

How do you programmatically extract the textures and other properties of an arbitrary Unity material?

Ideally runtime - I'm trying to upload the data to the server for remote access.

\$\endgroup\$
2
  • 2
    \$\begingroup\$ Have you tried the methods Material.GetTexture("TexturePropertyName")? \$\endgroup\$ Oct 22 '20 at 3:41
  • \$\begingroup\$ Can you loop through the property names for an arbitrary material whose property names you might not know in advance? So for something like .GetTexture(_property[i]) where _property[i] is the list of properties, how would you populate _property[i] \$\endgroup\$
    – ina
    Oct 22 '20 at 21:36
2
\$\begingroup\$

I think what you are looking for are the methods of Shader to get information about the properties and then as mentioned in the comments, use the methods of Material to get the data assigned to those properties (if any).

Below an example test where I check if the property is a texture, and log it if it is.

public class Example : MonoBehaviour
{
    public Material material;

    public void Start()
    {
        Shader shader = material.shader;

        for (int i = 0; i < shader.GetPropertyCount(); i++)
        {
            string propertyName = shader.GetPropertyName(i);
            var propertyType = shader.GetPropertyType(i);

            if (propertyType == UnityEngine.Rendering.ShaderPropertyType.Texture)
            {
                var texture = material.GetTexture(propertyName);
                Debug.Log(propertyName + " : " + texture?.name, texture);
            }
        }
    }
}
\$\endgroup\$
3
  • \$\begingroup\$ is there a typo texture?.name ? \$\endgroup\$
    – ina
    Oct 28 '20 at 3:25
  • \$\begingroup\$ I'm guessing you mean the question mark in there? This is not a typo, this '?.' is a null conditional operator It means: if lhs is null don't evaluate rhs and instead return null. Meaning if texture == null, texture?.name will return null instead of throw an error complaining texture is null. It is the same as this code: (texture == null ? null : texture.name) which would be similar to if(texture==null){return null;}else{return texture.name;}. \$\endgroup\$
    – troien
    Oct 28 '20 at 13:08
  • \$\begingroup\$ wow cool syntax! \$\endgroup\$
    – ina
    Oct 28 '20 at 18:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.