用到的相关API
AssetDatabase.FindAssets:获取目标路径下符合过滤器要求的所有资源的GUID(GUID是一个资源文件的唯一标识符)
AssetDatabase.GUIDToAssetPath:GUID转路径
PrefabUtility.LoadPrefabContents:载入给定路径的预制体
PrefabUtility.SaveAsPrefabAsset:保存预制体到指定路径
PrefabUtility.UnloadPrefabContents:释放通过LoadPrefabContents加载的预制体
示例代码
using UnityEditor;
using UnityEngine;
using System.Collections.Generic;
// 在编辑器中修改预制体
public class Fan_ModifyPrefabs
{
// 获取该目录下(包括其各子孙目录)的所有预制体
private static string path = "Assets/Fan";
[MenuItem("Fan/Add BoxCollider to Prefab")]
private static void AddBoxColliderToPrefab()
{
// 获取目标目录下所有预制体
Dictionary<string, GameObject> pathAndPrefabDict = new Dictionary<string, GameObject>();
string[] guids = AssetDatabase.FindAssets("t:prefab", new[] {path});
foreach (var guid in guids)
{
string path = AssetDatabase.GUIDToAssetPath(guid);
pathAndPrefabDict[path] = PrefabUtility.LoadPrefabContents(path);
}
// 为其添加BoxCollider
foreach (var path in pathAndPrefabDict.Keys)
{
GameObject prefab = pathAndPrefabDict[path];
if (prefab.GetComponent<BoxCollider>() == null)
{
prefab.AddComponent<BoxCollider>();
Debug.Log(string.Format("为{0}添加了碰撞体!", prefab.name));
PrefabUtility.SaveAsPrefabAsset(prefab, path);
}
else
{
Debug.Log(string.Format("{0}已有碰撞体,无法添加!", prefab.name));
}
PrefabUtility.UnloadPrefabContents(prefab);
}
}
}