Skip to content

Instantly share code, notes, and snippets.

@aholkner
Last active June 11, 2022 11:37
Show Gist options
  • Save aholkner/75aec99c02a35d8ee313296e91c4bc60 to your computer and use it in GitHub Desktop.
Save aholkner/75aec99c02a35d8ee313296e91c4bc60 to your computer and use it in GitHub Desktop.
Unity editor extension to create prefabs from asset menu
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<DoCreatePrefabAsset>());
}
[MenuItem("Assets/Create/Widget", isValidateFunction: false, priority: -20)]
public static void CreateWidget()
{
CreatePrefabAsset("New Widget", ScriptableObject.CreateInstance<DoCreateUIPrefabAsset>());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment