无法实现自动生成材质Material(Unity3D开发之十九)文章所说的功能,求大佬指教

Nonbady 2018-04-24 03:17:52
项目中,有时候导入一些资源时候,需要对应创建材质球,如果每次自己动手创建,还是挺麻烦的,下面是如何导入资源时候自动创建材质球。

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才会自动生成材质,所以使用时候,请自行修改下。

这里发现了个问题:
导入贴图时候,自动创建出来的材质球丢失了纹理图,而采用菜单按钮点击创建出来的正常。问题还没有解决,有哪位朋友知道解决办法可以告诉我下。
...全文
918 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
小黑仔呀仔 2018-05-09
  • 打赏
  • 举报
回复
使用OnPostprocessAllAssets。

2,535

社区成员

发帖
与我相关
我的任务
社区描述
Unity3D相关内容讨论专区
游戏unity 技术论坛(原bbs)
社区管理员
  • Unity3D
  • 芝麻粒儿
  • 「已注销」
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

Unity3D社区公告:

  1. 社区致力于解决各种Unity3D相关的“疑难杂症”。
  2. 社区不允许发布与Unity3D或相关技术无关内容。
  3. 社区版主邀请各位一道为打造优秀社区不懈努力。

试试用AI创作助手写篇文章吧