在項目開發中會經常性的更換、導入很多資源,而且對于資源的設定容易出現設定錯誤或者忘記設定的情況,下面的Code是用untyi自帶的 AssetPostprocessor 功能把導入的資源根據一定的規則自動設定對應的格式選項,使用的時候也很友善,隻需要把腳本放在Editor檔案夾下就可以
代碼有相應的注釋 可根據項目需求自定義即可,例如按照下面代碼的例子是圖檔名稱含有_UI字段的情況下(不分大小寫),圖檔對應的TextureType自動設定成Sprite,音頻之類的也是類似這種機制,模型方面會有精度壓縮,在不影響模型效果的情況下降低對應的Asstbundle包體
簡單示例如下
Unity 之 自動設定導入資源屬性選項(模型、圖檔、聲音) using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using UnityEngine.UI;
using System.Text.RegularExpressions;
using System;
public class EditorResourceSetting : AssetPostprocessor
{
#region 模型處理
//模型導入之前調用
public void OnPreprocessModel()
{
Debuger.Log("模型導入之前調用=" + this.assetPath);
ModelImporter modelImporter = (ModelImporter)assetImporter;
//模型優化
//modelImporter.optimizeMesh = true;
modelImporter.optimizeGameObjects = true;
modelImporter.animationCompression = ModelImporterAnimationCompression.Optimal;
modelImporter.animationRotationError = 1.0f;
modelImporter.animationPositionError = 1.0f;
modelImporter.animationScaleError = 1.0f;
}
//模型導入之後調用
public void OnPostprocessModel(GameObject go)
{
// for skeleton animations.
Debuger.Log("模型導入之後調用 ");
List<AnimationClip> animationClipList = new List<AnimationClip>(AnimationUtility.GetAnimationClips(go));
if (animationClipList.Count == 0)
{
AnimationClip[] objectList = UnityEngine.Object.FindObjectsOfType(typeof(AnimationClip)) as AnimationClip[];
animationClipList.AddRange(objectList);
}
foreach (AnimationClip theAnimation in animationClipList)
{
try
{
// 去除scale曲線
//foreach (EditorCurveBinding theCurveBinding in AnimationUtility.GetCurveBindings(theAnimation))
//{
// string name = theCurveBinding.propertyName.ToLower();
// if (name.Contains("scale"))
// {
// AnimationUtility.SetEditorCurve(theAnimation, theCurveBinding, null);
// }
//}
// 浮點數精度壓縮到f3
AnimationClipCurveData[] curves = null;
curves = AnimationUtility.GetAllCurves(theAnimation);
Keyframe key;
Keyframe[] keyFrames;
for (int ii = 0; ii < curves.Length; ++ii)
{
AnimationClipCurveData curveDate = curves[ii];
if (curveDate.curve == null || curveDate.curve.keys == null)
{
//Debuger.LogWarning(string.Format("AnimationClipCurveData {0} don't have curve; Animation name {1} ", curveDate, animationPath));
continue;
}
keyFrames = curveDate.curve.keys;
for (int i = 0; i < keyFrames.Length; i++)
{
key = keyFrames[i];
key.value = float.Parse(key.value.ToString("f3"));
key.inTangent = float.Parse(key.inTangent.ToString("f3"));
key.outTangent = float.Parse(key.outTangent.ToString("f3"));
keyFrames[i] = key;
}
curveDate.curve.keys = keyFrames;
theAnimation.SetCurve(curveDate.path, curveDate.type, curveDate.propertyName, curveDate.curve);
Debuger.Log("設定數值");
}
}
catch (System.Exception e)
{
Debuger.LogError(string.Format("CompressAnimationClip Failed !!! animationPath : {0} error: {1}", assetPath, e));
}
}
}
#endregion
#region 紋理處理
/// <summary>
/// 檢索Texture的類型是否為Sprite
/// </summary>
private string RetrivalTextureType = @"[_][Uu][Ii]";
/// <summary>
/// 檢索Texture的MaxSize大小
/// </summary>
private string RetrivalTextureMaxSize = @"[&]\d{2,4}";
/// <summary>
/// 檢索Texture是否為帶Alpha通道
/// </summary>
private string RetrivalTextureIsAlpha = @"[Aa][Ll][Pp][Hh][Aa]";
//紋理導入之前調用,針對入到的紋理進行設定
public void OnPreprocessTexture()
{
string dirName = System.IO.Path.GetDirectoryName(assetPath);
Debuger.Log(dirName);//從Asset開始的目錄資訊
string folderStr = System.IO.Path.GetFileName(dirName);
Debuger.Log(folderStr);//最近檔案夾資訊
TextureImporter textureImporter = (TextureImporter)assetImporter;
Debuger.Log(assetPath);//從Asset開始全路徑
string FileName = System.IO.Path.GetFileName(assetPath);
Debuger.Log("導入檔案名稱:" + FileName);
string[] FileNameArray = FileName.Split(new string[] { "_" }, System.StringSplitOptions.RemoveEmptyEntries);
//含有UI指定字元,此圖檔是的類型為Sprite
if (Regex.IsMatch(FileName, RetrivalTextureType))
{
Debuger.Log("含有指定字元");
textureImporter.textureType = TextureImporterType.Sprite;
textureImporter.mipmapEnabled = false;
}
else
{
textureImporter.textureType = TextureImporterType.Default;
//textureImporter.mipmapEnabled = true;
}
//判斷是否使用Alpha通道
if (Regex.IsMatch(FileName, RetrivalTextureIsAlpha))
{
textureImporter.alphaIsTransparency = true;
}
else
{
textureImporter.alphaIsTransparency = false;
}
// 設定MaxSize尺寸
Regex tempRegex = new Regex(RetrivalTextureMaxSize);
if (tempRegex.IsMatch(FileName))
{
string MaxSizeStr = tempRegex.Match(FileName).Value.Replace("&", "");
int TempMaxSize = Convert.ToInt32(MaxSizeStr);
if (TempMaxSize < 50)
{
TempMaxSize = 32;
}
else if (TempMaxSize < 100)
{
TempMaxSize = 64;
}
else if (TempMaxSize < 150)
{
TempMaxSize = 128;
}
else if (TempMaxSize < 300)
{
TempMaxSize = 256;
}
else if (TempMaxSize < 600)
{
TempMaxSize = 512;
}
else
{
TempMaxSize = 1024;
}
textureImporter.maxTextureSize = TempMaxSize;
Debuger.Log("設定的Texture尺寸為:" + TempMaxSize);
}
#region -------------------------根據平台分别設定-------------------------------------
// Debuger.Log("名稱:" + textureImporter.GetDefaultPlatformTextureSettings().name);
// TextureImporterPlatformSettings TempTexture = new TextureImporterPlatformSettings();
// TempTexture.overridden = true;
// TempTexture.name = "Android";
// TempTexture.maxTextureSize = 512;
// TempTexture.format = TextureImporterFormat.ETC_RGB4;
// textureImporter.SetPlatformTextureSettings(TempTexture);
// textureImporter.wrapMode = TextureWrapMode.Clamp;
//textureImporter.maxTextureSize = 1024;
//textureImporter.textureCompression = TextureImporterCompression.Compressed;
//textureImporter.crunchedCompression = true;
//textureImporter.compressionQuality = 60;
#endregion
}
public void OnPostprocessTexture(Texture2D tex)
{
Debuger.Log("導入" + "tex" + "圖檔後處理");
}
void OnPostprocessSprites(Texture2D texture, Sprite[] sprites)
{
Debuger.Log("Sprites: " + sprites.Length);
Debuger.Log("Texture2D: " + texture.name);
}
#endregion
#region 音頻處理
public void OnPreprocessAudio()
{
Debuger.Log("音頻導前預處理");
AudioImporterSampleSettings AudioSetting = new AudioImporterSampleSettings();
//加載方式選擇
AudioSetting.loadType = AudioClipLoadType.CompressedInMemory;
//壓縮方式選擇
AudioSetting.compressionFormat = AudioCompressionFormat.Vorbis;
//設定播放品質
AudioSetting.quality = 0.1f;
//優化采樣率
AudioSetting.sampleRateSetting = AudioSampleRateSetting.OptimizeSampleRate;
AudioImporter audio = assetImporter as AudioImporter;
//開啟單聲道
audio.forceToMono = true;
audio.preloadAudioData = true;
audio.defaultSampleSettings = AudioSetting;
}
public void OnPostprocessAudio(AudioClip clip)
{
Debuger.Log("音頻導後處理");
}
#endregion
#region 其他處理
//所有的資源的導入,删除,移動,都會調用此方法,注意,這個方法是static的 (這個是在對應資源的導入前後函數執行後觸發)
//public static void OnPostprocessAllAssets(string[] importedAsset, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)
//{
// Debuger.Log("EditorResourceSetting", "有檔案處理");
// foreach (string str in importedAsset)
// {
// Debuger.Log("導入檔案 = " + str);
// }
// foreach (string str in deletedAssets)
// {
// Debuger.Log("删除檔案 = " + str);
// }
// foreach (string str in movedAssets)
// {
// Debuger.Log("移動前檔案 = " + str);
// }
// foreach (string str in movedFromAssetPaths)
// {
// Debuger.Log("移動後檔案 = " + str);
// }
//}
/// <summary>
/// 在對應的資源已經設定Assetbundle名稱後更改其名稱觸發
/// </summary>
/// <param name="assetPath"></param>
/// <param name="previousAssetBundleName"></param>
/// <param name="newAssetBundleName"></param>
public void OnPostprocessAssetbundleNameChanged(string assetPath, string previousAssetBundleName, string newAssetBundleName)
{
Debuger.Log("AssetBundle資源 " + assetPath + " 從名稱: " + previousAssetBundleName + " 變更到: " + newAssetBundleName + ".");
}
/// <summary>
/// 模型 max、maya數值相關
/// </summary>
/// <param name="go"></param>
/// <param name="propNames"></param>
/// <param name="values"></param>
void OnPostprocessGameObjectWithUserProperties(GameObject go, string[] propNames, System.Object[] values)
{
//for (int i = 0; i < propNames.Length; i++)
//{
// string propName = propNames[i];
// System.Object value = (System.Object)values[i];
// Debug.Log("Propname: " + propName + " value: " + values[i]);
// if (value.GetType().ToString() == "System.Int32")
// {
// int myInt = (int)value;
// // do something useful
// }
// // etc...
//}
}
/// <summary>
/// 模型 貼圖相關
/// </summary>
/// <param name="material"></param>
/// <param name="renderer"></param>
public void OnAssignMaterialModel(Material material, Renderer renderer)
{
//Debug.Log("OnAssignMaterialModel");
}
//void OnPostprocessMaterial(Material material)
//{
// material.color = Color.red;
// Debuger.Log("更改材質球");
//}
//将該函數添加到子類中,以便在導入模型(.fbx,.mb檔案等)的動畫之前擷取通知。 這使您可以通過代碼控制導入設定。
void OnPreprocessAnimation()
{
//Debuger.Log("OnPreprocessAnimation");
//var modelImporter = assetImporter as ModelImporter;
//modelImporter.clipAnimations = modelImporter.defaultClipAnimations;
}
//private uint m_Version = 0;
//public override uint GetVersion() { return m_Version; }
#endregion
}