Last Updated: November 19, 2020
·
6.697K
· pekalicious

Asset Post Processor in Unity

Tired of setting the correct import settings on your texture for every single one of them? What about setting the audio to compressed? What if you could create a prefab based on the asset name? Automatically add components?

All these and more can be automated with Unity's Asset Post Processors!

The quick example below demonstrates changing the texture import settings for any filename that contains the string "atlas" and inverting the color of any texture that contains the string "invert_color":

public class CustomPostprocessor : AssetPostprocessor
{
    // Before the texture is imported
    public void OnPreprocessTexture()
    {
        // Apple settings to all atlases
        if (assetPath.Contains("_atlas"))
        {
            TextureImporter textureImporter = (TextureImporter)assetImporter;
            textureImporter.textureType = TextureImporterType.Advanced;
            textureImporter.mipmapEnabled = false;
            // All your import settings for atlases
        }
    }

    // After the texture is imported
    public void OnPostprocessTexture(Texture2D texture) 
    {
        // Invert colors
        if (assetPath.Contains("_invert_color"))
        {
            for (int m = 0; m < texture.mipmapCount; m++) 
            {
                Color[] c = texture.GetPixels(m);
                for (int i = 0; i < c.Length; i++) 
                {
                    c[i].r = 1 - c[i].r;
                    c[i].g = 1 - c[i].g;
                    c[i].b = 1 - c[i].b;
                }
                texture.SetPixels(c, m);
            }
        }
    }
}

More at: http://answers.unity3d.com/questions/14703/how-to-start-coding-with-assetpostprocessor.html

Related protips:

Improved PlayerPrefs for Unity