话不多说 直接上代码
原理就是 每次导入图片会触发OnPreprocessTexture() 做一次判断处理一下
但是每次图片改变都会调用 OnPreprocessTexture() 这个函数
如果防止频繁调用 自己加个标签记录一下吧(这里偷懒就不写了 (●’◡’●))
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.Reflection;
public class TextureSetting : AssetPostprocessor {
private void OnPreprocessTexture()
{
TextureImporter importer = (TextureImporter)assetImporter;
SetPicFormat (importer);
}
public static void SetPicFormat(TextureImporter imp)
{
//判断图片大小
int width = 0;
int hight = 0;
GetTextureSizeByImp (imp, out width, out hight);
Debug.LogErrorFormat ("term test cur image width: {0} hight: {1}",width,hight);
int sizeType = FitSize (Mathf.Max (width, hight));
if (imp.DoesSourceTextureHaveAlpha ())
{
//ios
imp.SetPlatformTextureSettings ("iphone", sizeType, TextureImporterFormat.ASTC_RGBA_6x6);
//android
imp.SetPlatformTextureSettings ("Android", sizeType, TextureImporterFormat.ETC2_RGBA8);
}
else
{
//ios
imp.SetPlatformTextureSettings ("iphone", sizeType, TextureImporterFormat.ASTC_RGB_6x6);
//android
imp.SetPlatformTextureSettings ("Android", sizeType, TextureImporterFormat.ETC2_RGB4);
}
}
static int[] formatSize = new int[]{ 32, 64, 128, 256, 512, 1024, 2048, 4096 };
static int FitSize(int picValue)
{
foreach (var one in formatSize)
{
if (picValue <= one)
{
return one;
}
}
return 1024;
}
static void GetTextureSizeByImp(TextureImporter imp, out int width,out int hight)
{
object[] args = new object[2]{ 0, 0 };
MethodInfo mi = typeof(TextureImporter).GetMethod ("GetWidthAndHeight", BindingFlags.NonPublic | BindingFlags.Instance);
mi.Invoke (imp, args);
width = (int)args [0];
hight = (int)args [1];
}
}