工程
示例代码
using UnityEngine;
using UnityEditor;
using System;
using System.IO;
using System.Collections;
public class MenuEditor {
[MenuItem("Tool/Texture SplitAlphaChannel ")]
static void SplitAlphaChannel()
{
Texture2D tex = Selection.activeObject as Texture2D;
if (null == tex)
return;
string texPath = AssetDatabase.GetAssetPath(tex);
string texDir = Path.GetDirectoryName(texPath);
string texName = Path.GetFileNameWithoutExtension(texPath);
//获取选中的Texture并设置导入参数
AssetImporter importer = AssetImporter.GetAtPath(texPath);
TextureImporter texImporter = importer as TextureImporter;
if (!texImporter.DoesSourceTextureHaveAlpha())
{
Debug.Log("当前选中的纹理图片没Alpha通道");
return;
}
texImporter.textureType = TextureImporterType.Advanced;
texImporter.isReadable = true;//开启读写
AssetDatabase.ImportAsset(texPath);
Color32[] colors32 = tex.GetPixels32();
//创建RGB Texture
Texture2D texrgb = new Texture2D(tex.width, tex.height, TextureFormat.RGB24, false);
texrgb.SetPixels32(colors32);
texrgb.Apply();
//保存RGB Texture
string texrgbPath = string.Format("{0}/Atlas/{1}_rgb.png", texDir, texName);
SavePNG(texrgbPath, texrgb);
for (int i = 0; i < colors32.Length; i++) {
colors32[i].r = colors32[i].a;
colors32[i].g = colors32[i].a;
colors32[i].b = colors32[i].a;
}
//创建Alpha Texture
Texture2D texalpha = new Texture2D(tex.width, tex.height, TextureFormat.RGB24, true);
texalpha.SetPixels32(colors32);
texalpha.Apply();
//保存Alpha Texture
string texalphaPath = string.Format("{0}/Atlas/{1}_alpha.png", texDir, texName);
SavePNG(texalphaPath, texalpha);
//平台设置
SetPlatformTextureSettings(texrgbPath);
SetPlatformTextureSettings(texalphaPath);
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
}
//平台设置
static void SetPlatformTextureSettings(string path)
{
TextureImporter texImporter = AssetImporter.GetAtPath(path) as TextureImporter;
texImporter.textureType = TextureImporterType.Advanced;
texImporter.mipmapEnabled = false;
int maxSize = 1024;
int quality = (int)TextureCompressionQuality.Normal;
//平台字符串 "Standalone", "iPhone", "Android", "WebGL", "Windows Store Apps", "PSP2", "PS4", "XboxOne", "Nintendo 3DS", "WiiU", "tvOS"
texImporter.SetPlatformTextureSettings("Standalone", maxSize, TextureImporterFormat.DXT5, quality);
texImporter.SetPlatformTextureSettings("iPhone", maxSize, TextureImporterFormat.PVRTC_RGBA4, quality);
texImporter.SetPlatformTextureSettings("Android", maxSize, TextureImporterFormat.ETC_RGB4, quality);
//texImporter.SetPlatformTextureSettings("Android", 1024, TextureImporterFormat.ETC2_RGBA8);//OpenGL ES 3.0才支持ETC2(支持Alpha通道)
}
//保存Texture
static void SavePNG(string filePath, Texture2D texture)
{
if (null == texture)
return;
try
{
string dir = Path.GetDirectoryName(filePath);
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
byte[] pngData = texture.EncodeToPNG();
File.WriteAllBytes(filePath, pngData);
}
catch (Exception ex)
{
Debug.Log(ex.StackTrace);
}
}
}
效果