CreatePrefabFromSelected

 avatar
unknown
csharp
4 years ago
2.2 kB
3
Indexable
using System;
using UnityEditor;
using UnityEngine;
using System.Collections;
using System.IO;

namespace AWWorldEditor
{
    class CreatePrefabFromSelected : ScriptableObject
    {
        const string menuTitle = "Tools/Axeyworks/Create Prefab(s) From Selected";

        [MenuItem(menuTitle, false, 304)]
        static void CreatePrefab()
        {
            var objs = Selection.gameObjects;
            string pathBase = EditorUtility.SaveFolderPanel("Choose save folder", "Assets", "");

            if (!String.IsNullOrEmpty(pathBase))
            {

                pathBase = pathBase.Remove(0, pathBase.IndexOf("Assets")) + Path.DirectorySeparatorChar;

                foreach (var go in objs)
                {
                    String localPath = pathBase + go.name + ".prefab";

                    localPath = localPath.Replace('\\', '/');

                    if (AssetDatabase.LoadAssetAtPath(localPath, typeof(GameObject)))
                    {
                        if (EditorUtility.DisplayDialog("Are you sure?",
                            "The prefab already exists." + "\n" + "Do you want to overwrite it?",
                            "Yes",
                            "No"))
                            CreateNew(go, localPath);
                    }
                    else
                    {
                        CreateNew(go, localPath);
                    }
                }
            }
        }

        static void CreateNew(GameObject obj, string localPath)
        {
            localPath = localPath.Replace('\\', '/');

#if UNITY_2018_3_OR_NEWER
            PrefabUtility.SaveAsPrefabAssetAndConnect(obj, localPath, InteractionMode.UserAction);
            AssetDatabase.Refresh();
#else
            UnityEngine.Object prefab = PrefabUtility.CreatePrefab(localPath, obj);
            PrefabUtility.ReplacePrefab(obj, prefab, ReplacePrefabOptions.ConnectToPrefab);
            AssetDatabase.Refresh();
#endif
        }

        [MenuItem(menuTitle, true, 5000)]
        static bool ValidateCreatePrefab()
        {
            return Selection.activeGameObject != null;
        }
    }
}
Editor is loading...