instanceRoot | 要更新的预制体实例的根节点。 |
强制预制体实例与来自预制体资源的更改合并。
在大多数情况下,当您在编辑器中或通过脚本进行更改时,Unity 会处理预制体实例的重新合并。但是,如下面的示例所示,在某些罕见情况下,从脚本编辑预制体实例需要您强制合并实例以获得即时更新。
如果您在这些罕见情况下没有调用 MergePrefabInstance,则重新合并将在当前帧结束时自动发生,但是如果您需要在脚本中立即反映更改,则必须强制合并。
using UnityEngine; using UnityEditor;
// This example shows how to use PrefabUtility.MergePrefabInstance to force update an instance after some changes
public class SuppressedComponentExample { public static void MergePrefabInstanceExample() { var instance = new GameObject("MyPrefabInstance"); const string path = "Assets/MyPrefab.prefab"; var prefab = PrefabUtility.SaveAsPrefabAssetAndConnect(instance, path, InteractionMode.AutomatedAction);
// Add Component to instance var component = instance.AddComponent<Rigidbody>();
// Add same type of component to the Prefab asset using (var scope = new PrefabUtility.EditPrefabContentsScope(path)) { scope.prefabContentsRoot.AddComponent<Rigidbody>(); }
// Because a Rigidbody already exists on the Prefab instance the one from the asset will be suppressed // we can get the suppressor and verify this var suppressor = instance.GetComponent<Rigidbody>(); Debug.Log($"Is component part of the Prefab instance: {PrefabUtility.IsPartOfPrefabInstance(suppressor)}");
// Destroy the suppressor to make the suppressed object return to glory Undo.DestroyObjectImmediate(suppressor); PrefabUtility.MergePrefabInstance(instance);
// Now we will get the former suppressed component and verify that it is actually part of the prefab var formerSuppressed = instance.GetComponent<Rigidbody>(); Debug.Log($"Is component part of the Prefab instance: {PrefabUtility.IsPartOfPrefabInstance(formerSuppressed)}"); } }