using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO;
using System.Text;
using UnityEditor;
using UnityEditor.Animations;
/// <summary>
/// 自動生成Prefab,只需要資源按照一定的目錄規范就可以
/// </summary>
public static class PrefabTools
{
[MenuItem("KTools/Prefab生成", false, 100)]
public static void GenerateCode()
{
// YanLingFaShi假定是每個模型的資源根目錄
// 根據選擇的目錄文件,其中包含了FBX文件,程序生成的controller文件,自動生成prefab,綁定animator
string targetPath = @"Assets\Resources\Prefabs";
Object[] objects = Selection.GetFiltered(typeof(object), SelectionMode.Assets);
if (objects.Length == 0)
{
Debug.LogWarning("請選擇資源目錄后再進行操作");
return;
}
foreach (var obj in objects)
{
string assetPath = AssetDatabase.GetAssetPath(obj);
string parentName = Path.GetDirectoryName(assetPath);
parentName = Path.GetFileNameWithoutExtension(parentName);
string ctrlName = Path.GetFileNameWithoutExtension(assetPath);
Debug.LogWarning("處理目錄:" + assetPath);
//Debug.LogWarning(parentName);
//Debug.LogWarning(ctrlName);
CreatePrefab(assetPath, targetPath + $"/{parentName}/{ctrlName}.prefab");
}
AssetDatabase.Refresh();
AssetDatabase.SaveAssets();
}
/// <summary>
/// 創建模型Prefab,可以對應創建規則內的Materials,綁定貼圖等等
/// </summary>
/// <param name="path"></param>
/// <param name="outPath"></param>
public static bool CreatePrefab(string path, string outPath)
{
EditorPathUtils.SaveCreateFolder(Path.GetDirectoryName(outPath));
// 該篩選器字符串可以包含:名稱、資產標簽(l)和類型(t類名稱)的搜索數據
// Mesh AnimationClip Material,等等都在里面
string[] fbxGUIDs = AssetDatabase.FindAssets("t:Object", new string[] { path });
//string[] ctrlGUIDs = AssetDatabase.FindAssets("t:AnimatorController", new string[] { path });
// 提取fbx目錄和controller目錄
string fbxPath = null;
string ctrlPath = null;
foreach (var v in fbxGUIDs)
{
string path1 = AssetDatabase.GUIDToAssetPath(v);
string fileExt = Path.GetExtension(path1);
if (fileExt.Equals(".fbx", System.StringComparison.CurrentCultureIgnoreCase))
{
fbxPath = path1;
//Debug.Log(path1);
}
else if (fileExt.Equals(".controller", System.StringComparison.CurrentCultureIgnoreCase))
{
ctrlPath = path1;
}
}
if (string.IsNullOrEmpty(fbxPath))
{
Debug.LogWarning("該資源不存在對應的fbx文件,跳過生成, path =" + path);
return false;
}
Object asset = AssetDatabase.LoadAssetAtPath<Object>(fbxPath);
GameObject gobj = (GameObject)GameObject.Instantiate(asset);
//gobj.name = asset.name;
EditorUtility.SetDirty(gobj);
// 如果path對應的目錄下有動畫控制器文件,那么自動添加animator
if (!string.IsNullOrEmpty(ctrlPath))
{
// 先判斷一下,Unity默認有可能會創建這個組件
Animator anim = gobj.GetComponent<Animator>();
if (!anim)
{
anim = gobj.AddComponent<Animator>();
}
AnimatorController ctrl = AssetDatabase.LoadAssetAtPath<AnimatorController>(ctrlPath);
anim.runtimeAnimatorController = ctrl;
}
else
{
Animator anim = gobj.GetComponent<Animator>();
if (null != anim)
{
GameObject.DestroyImmediate(anim);
Debug.LogWarning("該Prefab不應該生成Animator組件,自動刪除, path =" + path);
}
}
PrefabUtility.SaveAsPrefabAsset(gobj, outPath);
GameObject.DestroyImmediate(gobj);
return true;
}
}