using System.Collections; using System.Collections.Generic; using System.IO; using UnityEngine; using UnityEditor; using UnityEditor.Experimental; using UnityEditor.ProjectWindowCallback; // Add "New Prefab" asset creation menu items. public static class CreatePrefabAssetEditorMenu { class DoCreatePrefabAsset : EndNameEditAction { // Subclass and override this method to create specialised prefab asset creation functions protected virtual GameObject CreateGameObject(string name) { return new GameObject(name); } public override void Action(int instanceId, string pathName, string resourceFile) { GameObject go = CreateGameObject(Path.GetFileNameWithoutExtension(pathName)); GameObject prefab = PrefabUtility.SaveAsPrefabAsset(go, pathName); GameObject.DestroyImmediate(go); } } class DoCreateUIPrefabAsset : DoCreatePrefabAsset { protected override GameObject CreateGameObject(string name) { var obj = new GameObject(name, typeof(RectTransform)); obj.layer = LayerMask.NameToLayer("UI"); // Add a child with CanvasRenderer so that the prefab editor knows to use the UI stage. var canvas = new GameObject("Image", typeof(CanvasRenderer), typeof(UnityEngine.UI.Image)); canvas.transform.SetParent(obj.transform, worldPositionStays: false); return obj; } } static void CreatePrefabAsset(string name, DoCreatePrefabAsset createAction) { string directory = GetSelectedAssetDirectory(); string path = Path.Combine(directory, $"{name}.prefab"); ProjectWindowUtil.StartNameEditingIfProjectWindowExists(0, createAction, path, EditorGUIUtility.FindTexture("Prefab Icon"), null); } static string GetSelectedAssetDirectory() { string path = AssetDatabase.GetAssetPath(Selection.activeObject); if (Directory.Exists(path)) return path; else return Path.GetDirectoryName(path); } [MenuItem("Assets/Create/Prefab", isValidateFunction: false, priority: -20)] public static void CreatePrefab() { CreatePrefabAsset("New Prefab", ScriptableObject.CreateInstance()); } [MenuItem("Assets/Create/Widget", isValidateFunction: false, priority: -20)] public static void CreateWidget() { CreatePrefabAsset("New Widget", ScriptableObject.CreateInstance()); } }