專案中,有時候匯入一些資源時候,需要對應創建材質球,如果每次自己動手創建,還是挺麻煩的,下面是如何匯入資源時候自動創建材質球。
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using UnityEditor;
using System.IO;
public class BuildMaterial : UnityEditor.AssetModificationProcessor
{
//生成出的Material的路徑
private static string MaterialsPath = "Assets/Resources/Skin/";
// 創建選單按鈕,手工呼叫創建材質
[MenuItem ("HETools/BuildMaterials")]
static void CreateMateral ()
{
Object[] selectObject = Selection.objects;
List<string> path = new List<string> ();
foreach (Object obj in selectObject) {
path.Add (AssetDatabase.GetAssetPath (obj));
}
foreach (string p in path) {
CreateOneMateral (p);
}
System.GC.Collect ();
}
// 監控assets資源添加,發現指定目錄ThemeTile有新增加的texture,就自動生成材質
public static void OnWillCreateAsset (string path)
{
int index = path.LastIndexOf (".");
string file = path.Substring (index);
string[] pathArr = path.Split ('/');
if (pathArr [pathArr.Length - 3] != "ThemeTile")
return;
CreateOneMateral (path);
System.GC.Collect ();
}
// 創建材質球
static void CreateOneMateral (string p)
{
p = p.Replace (".meta", "");
Debug.Log ("CreateOneMateral from path: " + p);
int pos = p.LastIndexOf ('/');
if (pos == -1)
return;
string[] strArr = p.Split ('/');
string themeIDStr = strArr [strArr.Length - 2];
Texture textur = (Texture)AssetDatabase.LoadAssetAtPath (p, typeof(Texture)) as Texture;
string name = strArr [strArr.Length - 1];
int y = name.IndexOf ('.');
name = name.Substring (0, y);
Material mater = new Material (Shader.Find ("Mobile/VertexLit"));
mater.mainTexture = textur;
AssetDatabase.CreateAsset (mater, MaterialsPath + themeIDStr + "/" + name + ".mat");
}
}

這里寫圖片描述
注意,上面代碼中我是規定了只有指定的目錄添加texture才會自動生成材質,所以使用時候,請自行修改下。
這里發現了個問題:
匯入貼圖時候,自動創建出來的材質球丟失了紋理圖,而采用選單按鈕點擊創建出來的正常。問題還沒有解決,有哪位朋友知道解決辦法可以告訴我下。
uj5u.com熱心網友回復:
使用OnPostprocessAllAssets。轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/51913.html
標籤:Unity3D
