Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Unity editor script to create prefab from selected game object.
using UnityEditor;
using UnityEngine;
/// <summary>
/// Creates a prefab from a selected game object.
/// </summary>
class CreatePrefabFromSelected
{
const string menuName = "GameObject/Create Prefab From Selected";
/// <summary>
/// Adds a menu named "Create Prefab From Selected" to the GameObject menu.
/// </summary>
[MenuItem(menuName)]
static void CreatePrefabMenu ()
{
var go = Selection.activeGameObject;
var prefab = EditorUtility.CreateEmptyPrefab("Assets/" + go.name + ".prefab");
EditorUtility.ReplacePrefab(go, prefab);
AssetDatabase.Refresh();
}
/// <summary>
/// Validates the menu.
/// The item will be disabled if no game object is selected.
/// </summary>
/// <returns>True if the menu item is valid.</returns>
[MenuItem(menuName, true)]
static bool ValidateCreatePrefabMenu ()
{
return Selection.activeGameObject != null;
}
}
@jareguo

This comment has been minimized.

Copy link

commented May 30, 2014

PrefabUtility.CreatePrefab

@mminer

This comment has been minimized.

Copy link
Owner Author

commented Nov 20, 2014

@jarequo: Indeed, this is redundant now. I'm unsure if PrefabUtility.CreatePrefab didn't exist when I wrote this script, or if I simply missed it.

@zornified

This comment has been minimized.

Copy link

commented Oct 17, 2016

it didn't exist when you wrote this article.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.