4.8 KiB
#unity/日常积累
PrefabUtility.SaveAsPrefabAsset
public static GameObject SaveAsPrefabAsset (GameObject instanceRoot, string assetPath);
public static GameObject SaveAsPrefabAsset (GameObject instanceRoot, string assetPath, out bool success);
参数
instanceRoot
要保存为预制件资源的游戏对象。
assetPath
要在其中保存预制件的路径。
success
保存操作的结果(成功或不成功)。将其与控制台日志一起使用,从而进一步了解保存过程。
返回
GameObject 已保存的预制件资源(如果可用)的根游戏对象。
描述
使用该函数,在给定路径上,从给定的游戏对象创建一个预制件资源(包括场景中的任何子项),而不修改输入对象。
如果某些子项是预制件实例,则会自动将这些子项嵌套在新预制件资源内。
The input object must be a plain GameObject or the outermost root of a Prefab Instance. It cannot be a child inside a Prefab instance.
如果输入对象是预制件实例根,则生成的预制件将是预制件变体。反之,如果要新建唯一的预制件,需要首先解压该预制件实例。
返回对象是已保存的预制件资源(如果可用)的根游戏对象。如果编辑器当前正在进行资源编辑批处理操作(使用 AssetDatabase.StartAssetEditing 和 AssetDatabase.StopAssetEditing 控制),则不会在保存时立即导入资源。在此情况下,SaveAsPrefabAsset 会返回 null,即使保存成功也是如此,因为保存的预制件资源尚未重新导入,从而尚不可用。
如果要对现有预制件进行保存,Unity 会尝试保留对预制件本身的引用以及预制件的各个部分(如子游戏对象和组件)。要执行此操作,它在新保存的预制件与现有预制件之间匹配游戏对象的名称。
注意:因为仅按名称进行此匹配,所以如果预制件的层级视图中有多个同名的游戏对象,则无法预测会匹配哪个游戏对象。因此,如果需要确保在对现有预制件进行保存时保留引用,则必须确保预制件中的所有游戏对象都具有唯一名称。
另请注意:当预制件中的单个游戏对象附加了多个相同组件类型时,如果在对现有预制件进行保存时保留对现有组件的引用,则可能会遇到相似问题。在此情况下,无法预测哪个组件会与现有引用匹配。
// This script creates a new menu item Examples>Create Prefab in the main menu.
// Use it to create Prefab(s) from the selected GameObject(s).
// Prefab(s) are placed in the "Prefabs" folder.
using System.IO;
using UnityEngine;
using UnityEditor;
public class Example
{
// Creates a new menu item 'Examples > Create Prefab' in the main menu.
[MenuItem("Examples/Create Prefab")]
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)
{
// Create folder Prefabs and set the path as within the Prefabs folder,
// and name it as the GameObject's name with the .Prefab format
if (!Directory.Exists("Assets/Prefabs"))
AssetDatabase.CreateFolder("Assets", "Prefabs");
string localPath = "Assets/Prefabs/" + gameObject.name + ".prefab";
// Make sure the file name is unique, in case an existing Prefab has the same name.
localPath = AssetDatabase.GenerateUniqueAssetPath(localPath);
// Create the new Prefab and log whether Prefab was saved successfully.
bool prefabSuccess;
PrefabUtility.SaveAsPrefabAsset(gameObject, localPath, out prefabSuccess);
if (prefabSuccess == true)
Debug.Log("Prefab was saved successfully");
else
Debug.Log("Prefab failed to save" + prefabSuccess);
}
}
// Disable the menu item if no selection is in place.
[MenuItem("Examples/Create Prefab", true)]
static bool ValidateCreatePrefab()
{
return Selection.activeGameObject != null && !EditorUtility.IsPersistent(Selection.activeGameObject);
}
}