web analytics

Texture Compression Tips : Unity OnPreprocessTexture

     Got tired of compressing every single texture ? , then this post is your savior . Unity Provides a method called OnPreprocessTexture , which is called right before any newly added texture is assigned default values. OnPreprocessTexture saves a lot of time . We all know how much time we spend in compressing a texture or loading it.

By Using the below script you can save yourself from that work.

using UnityEngine;
using UnityEditor;

public class MyTextureFormat : AssetPostprocessor
{
   	 void OnPreprocessTexture(){
   		 TextureImporter texImport = assetImporter as TextureImporter;
   		 texImport.textureType = TextureImporterType.Image;
   		 texImport.alphaIsTransparency = true;
   		 texImport.maxTextureSize = 512;
   		 texImport.textureFormat = TextureImporterFormat.AutomaticTruecolor;
   	 }
}

unity onpreprocesstexture 2

*   Make Sure that the script is in EDITOR folder.

As you can see that it now automatically changes the import settings.

I found only problem , you can’t override these properties explicitly from the Inspector . Lets say you have set the textureimporttype to Sprite (via Script), now if you want to change the import setting from the inspector ,you cant.

You will have to change the code for it. Now you are wondering what if you want to have some images of type “Sprite” , some “Normal Maps” and some “Texture“. You can do that by simply by naming the texture / adding a postfix to the name .

unity onpreprocesstexture,unity tips and tricks,unity onpreprocesstexture

name_sprite”  for the images you want to be of type sprite
name_texture” for the images you want to be of type Texture.

eg.

unity onpreprocesstexture 1

unity onpreprocesstexture,unity tips and tricks,unity onpreprocesstexture

The below script will compress depending on the image name.

/// <summary>
    /// By Using the below script you can save yourself from that work.
    /// </summary>
    void OnPreprocessTexture ()
    {
   	 TextureImporter texImport = assetImporter as TextureImporter;
    
   	 //assetPath is the name of the Image you are importing

   	 if (assetPath.Contains ("_sprite")) {

   		 texImport.textureType = TextureImporterType.Sprite;
   		 texImport.maxTextureSize = 512;
   		 texImport.textureFormat = TextureImporterFormat.AutomaticCompressed;

   	 } else if (assetPath.Contains ("_texture")) {

   		 texImport.textureType = TextureImporterType.Image;
   		 texImport.alphaIsTransparency = true;
   		 texImport.maxTextureSize = 512;
   		 texImport.textureFormat = TextureImporterFormat.AutomaticTruecolor;
   		 
   	 }
    }

You can even apply presettings to audio using OnPreprocessAudio.

unity onpreprocesstexture,unity tips and tricks,unity onpreprocesstexture

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *