版本: Unity 6 (6000.0)
语言English
  • C#

PrefabUtility.MergePrefabInstance

建议更改

成功!

感谢您帮助我们提高 Unity 文档的质量。虽然我们无法接受所有提交,但我们确实阅读了用户提出的每个建议更改,并在适用时进行更新。

关闭

提交失败

由于某种原因,您的建议更改无法提交。请<a>稍后再试</a>。感谢您抽出时间帮助我们提高 Unity 文档的质量。

关闭

取消

声明

public static void MergePrefabInstance(GameObject instanceRoot);

参数

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