public static GameObject ReplacePrefab (GameObject go, Object targetPrefab, ReplacePrefabOptions options= ReplacePrefabOptions.Default);

描述

targetPrefab 替换为游戏对象层级视图 go 的副本。

创建预制件游戏对象后返回该对象。 如果启用了 go,则 go 将成为已创建预制件的实例。

// Creates a prefab from the selected GameObjects.
// If the prefab already exists it asks if you want to replace it.

using UnityEngine; using UnityEditor;

public class ExampleClass : EditorWindow { [MenuItem("Examples/Create Prefab From Selected")] static void CreatePrefab() { GameObject[] objs = Selection.gameObjects;

foreach (GameObject go in objs) { string localPath = "Assets/" + go.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); } } }

// Disable the menu item if no selection is in place [MenuItem("Examples/Create Prefab From Selected", true)] static bool ValidateCreatePrefab() { return Selection.activeGameObject != null; }

static void CreateNew(GameObject obj, string localPath) { Object prefab = PrefabUtility.CreateEmptyPrefab(localPath); PrefabUtility.ReplacePrefab(obj, prefab, ReplacePrefabOptions.ConnectToPrefab); } }