您的位置:首页 > 移动开发 > Unity3D

Unity3d脚本改变GameObject的Material(二)

2016-06-16 10:08 393 查看
对所有 perfab进行扫描,并替换 Particle中的默认材质为自定义材质(主要用来依赖打包做准备)

using System;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;

public class ReplaceMaterial
{

static void SetObjRecursively(ref bool bFind ,GameObject rootObj,Material mat)
{
if (null == rootObj)
{
return;
}
if (null != rootObj.particleSystem)
{
if (null != rootObj.particleSystem.renderer)
{
if (null !=  rootObj.particleSystem.renderer.sharedMaterial
&&rootObj.particleSystem.renderer.sharedMaterial.name.Contains("Default-Particle"))
{
Debug.Log(rootObj.name);
rootObj.particleSystem.renderer.material = mat;
bFind = true;
}
}
}
System.Collections.Generic.IEnumerable<GameObject> subObj = rootObj.GetDirectChildren();
if (null != subObj)
{
System.Collections.Generic.IEnumerator<GameObject> e = subObj.GetEnumerator();
while (e.MoveNext())
{
SetObjRecursively(ref bFind, e.Current, mat);
}
}

}

static void ScanAllPrefabUseDefaultParticle()
{

List<string> perfabPathLs = new List<string>();
Debug.Log(Application.dataPath);
GetPerfabRecursively(Application.dataPath, "*.prefab", ref perfabPathLs);

int count = 0;
int totalcount = perfabPathLs.Count;
UnityEngine.Object matObj = AssetDatabase.LoadMainAssetAtPath("Assets/sfx/default_fx.mat");
Material mat = matObj as Material;

int replaceCount = 0;
foreach (var onePath in perfabPathLs)
{
UnityEngine.Object obj = AssetDatabase.LoadMainAssetAtPath(onePath);
UnityEngine.GameObject gObj = obj as UnityEngine.GameObject;
bool bFind = false;

SetObjRecursively(ref bFind, gObj, mat);
if (bFind)
{
Debug.Log(onePath);
replaceCount++;
AssetDatabase.SaveAssets();//可以在保存的时候检查到资源本身的错误
}
if (0 == (++count)%10)
{
EditorUtility.DisplayCancelableProgressBar("Scan perfab", "wait....", count * 1f / totalcount);
}
}
EditorUtility.ClearProgressBar();
//AssetDatabase.SaveAssets();
Debug.Log("Replace TotalCount:" + replaceCount);
}

static void GetPerfabRecursively(string srcFolder, string searchPattern, ref List<string> perfabLs)
{
//string searchPattern = "*.perfab";
string searchFolder = srcFolder.Replace(@"\", @"/");
string searchFolderTemp = searchFolder.ToLower();
if (Directory.Exists(searchFolderTemp))
{
string[] files = Directory.GetFiles(searchFolderTemp, searchPattern);
foreach (var onefile in files)
{
string srcFile = onefile.Replace(@"\", @"/");
string lowerFile =StanderPath( srcFile.ToLower());
perfabLs.Add(lowerFile);
}
string[] dirs = Directory.GetDirectories(searchFolderTemp);
foreach (string oneDir in dirs)
{
GetPerfabRecursively(oneDir, searchPattern, ref perfabLs);
}
}
}

static string StanderPath(string srcPath)
{
int index = srcPath.IndexOf("assets/");
string resultStr = srcPath.Substring(index, srcPath.Length - index);
return resultStr;
}

[MenuItem("EctypeEditor/Scan AllPerfab")]
static void ScanAllPrefab()
{
ScanAllPrefabUseDefaultParticle();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  unity3d