using UnityEditor;
using UnityEngine;
public class ExportObjects : EditorWindow
{
//Creates a new menu (Examples) with a menu item (Create Prefab)
[MenuItem("GameObject/Create Prefab", false, -1)]
static void CreatePrefab()
{
//Keep track of the currently selected GameObject(s)
GameObject[] objectArray = Selection.gameObjects;
//Loop through every GameObject in the array above
foreach (GameObject gameObject in objectArray)
{
//Set the path as within the Assets folder, and name it as the GameObject's name with the .prefab format
string localPath = "Assets/Prefabs to export/" + gameObject.name + ".prefab";
//Check if the Prefab and/or name already exists at the path
if (AssetDatabase.LoadAssetAtPath(localPath, typeof(GameObject)))
{
//Create dialog to ask if User is sure they want to overwrite existing Prefab
if (EditorUtility.DisplayDialog("Are you sure?",
"The Prefab already exists. Do you want to overwrite it?",
"Yes",
"No"))
//If the user presses the yes button, create the Prefab
{
CreateNew(gameObject, localPath);
Export(gameObject, localPath);
}
}
//If the name doesn't exist, create the new Prefab
else
{
Debug.Log(gameObject.name + " is not a Prefab, will convert");
CreateNew(gameObject, localPath);
Export(gameObject, localPath);
}
}
}
// Disable the menu item if no selection is in place
[MenuItem("GameObject/Create Prefab", true, -1)]
static bool ValidateCreatePrefab()
{
return Selection.activeGameObject != null;
}
static void CreateNew(GameObject obj, string localPath)
{
//Create a new Prefab at the path given
Object prefab = PrefabUtility.SaveAsPrefabAsset(obj, localPath);
PrefabUtility.ReplacePrefab(obj, prefab, ReplacePrefabOptions.ConnectToPrefab);
}
static void Export(GameObject obj, string localPath)
{
AssetDatabase.ExportPackage(localPath, obj.name);
}
}
第一个问题是在Export方法中。它到达那儿并开始生产线:
AssetDatabase.ExportPackage(localPath, obj.name);
但是它并没有在localPath的硬盘上创建任何程序包文件。
第二个问题是我不确定是否做错了,-1是正确的(但它可以正常工作)。
第三种更改方式:
PrefabUtility.ReplacePrefab(obj, prefab, ReplacePrefabOptions.ConnectToPrefab);
ReplacePrefab已过时,应该像之前的一行中那样替换:SaveAsPrefabAsset,我尝试过,但是在这一行中参数与上面的参数不同:obj,prefab,ReplacePrefabOptions.ConnectToPrefab所以我不确定该怎么做它。
答案 0 :(得分:1)
我相信没有创建软件包,因为您没有目录“ Prefabs to export”。 建议的一种方法是创建目录
string defaultPath = Application.dataPath + "/Prefabs to export/";
if (!Directory.Exists(defaultPath))
{
Directory.CreateDirectory(defaultPath);
}
如果您不存在该选项,则会创建该选项。它将到达AssetDatabase.ExportPackage,但是编辑器必须抛出一些错误。请检查编辑器日志。
在MenuItem中设置的问题-1的第二部分是按按钮在菜单中显示的顺序进行的。您可以根据需要将其设置为0或1甚至10。我相信菜单中最上方的按钮保持为0,因此将其设置为-1将使您的按钮位于Unity中其他按钮之上。
到目前为止,我还不知道任何替换方法,在深入研究之后,我发现根据Unity's team,它已被替换为过时标记。因此,您可以同时使用此Replace prefab,直到问题得到解决为止。
我们正在努力替代ReplacePrefab。同时,您可以继续使用过时的API。替换是在我们发货时完成的,但没有完成。在我们看来,旧方法标记为过时而未准备好替换是一个错误。抱歉给您带来不便。