自動生成材質Material(Unity3D開發之十九)
阿新 • • 發佈:2018-12-26
專案中,有時候匯入一些資源時候,需要對應建立材質球,如果每次自己動手建立,還是挺麻煩的,下面是如何匯入資源時候自動建立材質球。
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才會自動生成材質,所以使用時候,請自行修改下。
這裡發現了個問題:
匯入貼圖時候,自動創建出來的材質球丟失了紋理圖,而採用選單按鈕點選創建出來的正常。問題還沒有解決,有哪位朋友知道解決辦法可以告訴我下。