Unity 批量ApplyPrefab

using UnityEngine;
using System.Collections;
using UnityEditor;
public class ApplyPrefabEditor : Editor {
    [MenuItem("Ari/Batch Apply Prefab")]
    public static void BatchApplyPrefab()
    {
        GameObject[] objs = Selection.gameObjects;
        if (null == objs || objs.Length < 1)
        {
            Debug.LogError("沒有選中prefab");
            return;
        }
        for (int i = 0; i < objs.Length; i++)
        {
            ApplyPrefab(objs[i]);
        }
    }

    public static void ApplyPrefab(GameObject obj)
    {
        if (null == obj)
        {
            Debug.LogError("選中的obj 是 null");
            return;
        }
        PrefabType type = EditorUtility.GetPrefabType(obj);
        if (type != PrefabType.PrefabInstance)
        {
            Debug.LogError("選中的obj " + obj.name + "  不是 PrefabInstance ");
            return;
        }

        //這里必須獲取到prefab實例的根節點,否則ReplacePrefab保存不了
        GameObject prefabObj = GetPrefabInstanceParent(obj);
        UnityEngine.Object prefabAsset = null;
        if (prefabObj != null)
        {
            prefabAsset = PrefabUtility.GetPrefabParent(prefabObj);
            if (prefabAsset != null)
            {
                PrefabUtility.ReplacePrefab(prefabObj, prefabAsset, ReplacePrefabOptions.ConnectToPrefab);
                Debug.Log("PrefabInstance :" + prefabObj.name + "  Apply 成功");
            }
        }
        AssetDatabase.SaveAssets();
    }

    //遍歷獲取prefab節點所在的根prefab節點
    static GameObject GetPrefabInstanceParent(GameObject obj)
    {
        if (obj == null)
        {
            return null;
        }
        PrefabType pType = EditorUtility.GetPrefabType(obj);
        if (pType != PrefabType.PrefabInstance)
        {
            return null;
        }
        if (obj.transform.parent == null)
        {
            return obj;
        }
        pType = EditorUtility.GetPrefabType(obj.transform.parent.gameObject);
        if (pType != PrefabType.PrefabInstance)
        {
            return obj;
        }
        return GetPrefabInstanceParent(obj.transform.parent.gameObject);
    }
    
}
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容