自己主动生成材质Material(Unity3D开发之十九)

时间:2022-11-30 14:29:50

猴子原创,欢迎转载。转载请注明: 转载自Cocos2Der-CSDN,谢谢!

原文地址: http://blog.csdn.net/cocos2der/article/details/46854411

项目中,有时候导入一些资源时候。须要相应创建材质球。假设每次自己动手创建。还是挺麻烦的,以下是怎样导入资源时候自己主动创建材质球。

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/"; // 创建菜单button。手工调用创建材质
[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");
}
}

自己主动生成材质Material(Unity3D开发之十九)

注意,上面代码中我是规定了仅仅有指定的文件夹加入texture才会自己主动生成材质,所以使用时候。请自行改动下。

这里发现了个问题:

导入贴图时候,自己主动创建出来的材质球丢失了纹理图。而採用菜单button点击创建出来的正常。问题还没有解决,有哪位朋友知道解决的方法能够告诉我下。