1. 程式人生 > >Unity3d指令碼改變GameObject的Material(二)

Unity3d指令碼改變GameObject的Material(二)

對所有 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(); } }