I wrote this class to streamline import settings on a bunch of UI textures. In addition to setting import settings, I want to create a material for each texture. This works great if I use "Reimport" from Unity after the textures have been imported, but upon the first automatic import, the material's texture is never set. It's as if:
(Texture2D)AssetDatabase.LoadAssetAtPath(assetPath,typeof(Texture2D));
returns null. Note that this is the only technique I could figure out in order to get a reference to the current asset being imported. It seems like there would be a built-in pointer to it, but I found nothing in the docs. Does anyone know why that would return null upon first import? Or if there is a better way to get a reference to the Texture2D that is being imported so I don't have to look it up using LoadAssetAtPath() ?
[Edited the code to reflect the answer below.]
using UnityEngine;
using System.IO;
using System.Collections;
using UnityEditor;
public class UITextureImport : AssetPostprocessor
{
void OnPreprocessTexture()
{
if (assetPath.Contains("Assets/Textures/UI/") && assetPath.Contains(".png"))
{
// Set specific properties for UI textures.
TextureImporter textureImporter = (TextureImporter)assetImporter;
textureImporter.textureType = TextureImporterType.Advanced;
textureImporter.textureFormat = TextureImporterFormat.AutomaticTruecolor;
textureImporter.mipmapEnabled = false;
textureImporter.filterMode = FilterMode.Point;
textureImporter.wrapMode = TextureWrapMode.Clamp;
}
}
void OnPostprocessTexture(Texture2D texture)
{
if (assetPath.Contains("Assets/Textures/UI/") && assetPath.Contains(".png"))
{
// Create a matching material if one doesn't exist.
string materialPath = assetPath.Replace("Assets/Textures/UI/","Assets/Materials/UI/");
materialPath = materialPath.Substring(0,assetPath.LastIndexOf("/") + 1);
if (!Directory.Exists(materialPath))
{
Directory.CreateDirectory(materialPath);
}
materialPath += "/" + Path.GetFileNameWithoutExtension(assetPath) + ".mat";
Material material = (Material)AssetDatabase.LoadAssetAtPath(materialPath,typeof(Material));
if (material == null)
{
// Material doesn't exist, so create it now.
material = new Material(Shader.Find("UnlitAlphaImage"));
material.mainTexture = texture;
AssetDatabase.CreateAsset(material, materialPath);
}
else
{
// Material exists, so only assign the new texture to it.
material.mainTexture = texture;
}
}
}
}