Skip to content

Instantly share code, notes, and snippets.

@nomadalex
Created September 7, 2011 03:22
Show Gist options
  • Save nomadalex/1199674 to your computer and use it in GitHub Desktop.
Save nomadalex/1199674 to your computer and use it in GitHub Desktop.
Unity中从目前选择对象创建预设(Prefab)脚本
using UnityEditor;
using UnityEngine;
using System.Collections;
class CreatePrefabFromSelected : ScriptableObject
{
const string menuTitle = "GameObject/Create Prefab From Selected";
/// <summary>
/// Creates a prefab from the selected game object.
/// </summary>
[MenuItem(menuTitle)]
static void CreatePrefab()
{
GameObject[] obj = Selection.gameObjects;
foreach (GameObject go in obj)
{
string name = go.name;
string localPath = "Assets/" + name + ".prefab";
if (AssetDatabase.LoadAssetAtPath(localPath, typeof(GameObject)))
{
if (EditorUtility.DisplayDialog("Are you sure?", "The prefab already exists. Do you want to overwrite it?", "Yes", "No"))
{
createNew(go, localPath);
}
}
else
{
createNew(go, localPath);
}
}
}
static void createNew(GameObject obj, string localPath)
{
Object prefab = EditorUtility.CreateEmptyPrefab(localPath);
EditorUtility.ReplacePrefab(obj, prefab);
AssetDatabase.Refresh();
DestroyImmediate(obj);
GameObject clone = EditorUtility.InstantiatePrefab(prefab) as GameObject;
}
/// <summary>
/// Validates the menu.
/// </summary>
/// <remarks>The item will be disabled if no game object is selected.</remarks>
[MenuItem(menuTitle, true)]
static bool ValidateCreatePrefab()
{
return Selection.activeGameObject != null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment