How to catch Material doesn't have a texture property exception

Hi everyone,
I have following code

using UnityEngine;
using System.Collections;
using UnityEditor;
using System.Collections.Generic;
using System;   
public class UFTMaterialUtil {	
	public static List<Texture> getTextures(Material material){
		Shader shader=material.shader;			
		List<Texture> textures=new List<Texture>();
		for (int i = 0; i < ShaderUtil.GetPropertyCount(shader) ; i++) {						
			if (ShaderUtil.GetPropertyType(shader,i) == ShaderUtil.ShaderPropertyType.TexEnv){
				string propertyName=ShaderUtil.GetPropertyName(shader,i);
				try {					
					textures.Add( material.GetTexture(propertyName));						
				} catch (Exception ex) {
					Debug.Log("EXCEPTION_________"+ex);
				}				
			}			
		}
		return textures;
	}	
}

the problem is here (row14)
materials.add( material.GetTexture(propertyName));
if material has property, assume _MainTex, but non of texture is assigned to it,
Unity instead of catch exception and show log, show this error

Material doesn’t have a texture property ‘_MainTex’
UnityEngine.Material:GetTexture(String)
UFTMaterialUtil:getTextures(Material) (at Assets/UFTAtlasEditor/Resources/Scripts/Utils/UFTMaterialUtil.cs:25)
UFTAtlasMigrateWindow:getMaterialListByAtlasMetadata(UFTAtlasMetadata) (at Assets/UFTAtlasEditor/Editor/UFTAtlasMigrateWindow.cs:113)
UFTAtlasMigrateWindow:displayUpdateLinksToTextureMaterial() (at Assets/UFTAtlasEditor/Editor/UFTAtlasMigrateWindow.cs:90)
UFTAtlasMigrateWindow:OnGUI() (at Assets/UFTAtlasEditor/Editor/UFTAtlasMigrateWindow.cs:71)
UnityEditor.DockArea:OnGUI()

1 Answer

1

You could use material.HasProperty()

 if (renderer.material.HasProperty(propertyName))
     textures.Add(material.GetTexture(propertyName));   

I tried this method before, but unfortunately it won't help, because HasProperty() return every time. this method is not the same as IsPropertySet which is missed.

Thanks for sharing :)