Unity中从目前选择对象创建预设(Prefab)脚本

在Unity中选择一个游戏对象,然后通过这个脚本来快速生成一个Prefab预设.
将脚本放在Editor文件夹中,选择游戏对象,支持多选,然后选择菜单GameObject > Create Prefab From Selection,就会在根目录生成一个预设,名字和选择的游戏对象一样.当已经存在同名的预设,将会提示是否覆盖.

脚本名:CreatePrefabFromSelected.cs

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;
    }
}

原文:http://www.unifycommunity.com/wiki/index.php?title=CreatePrefabFromSelected

发布于 :未分类

发表评论

电子邮件地址不会被公开。