-1

从 v2020.3 开始,Unity 仍然没有为我们提供干净的 API 来通过脚本应用单个预制件的覆盖。

本质上是一个干净的单线,真正反映了“应用预制”的概念,包括异常处理。

这是过时的,因为它使用了已弃用的功能 https://forum.unity.com/threads/apply-changes-to-prefab-keyboard-shortcut.29251/#post-2538088

4

1 回答 1

0

与此斗争了一段时间后,当前的脚本如下。希望它可以作为构建适合您的自定义工作流程的基础。

using UnityEditor;
using UnityEngine;

public static class Editor_Helper
{
    [MenuItem("Editor/Apply Selected Prefab &[")]
    public static void ApplySelectedPrefab()
    {
        GameObject gO = GetCurrentlySelectedObjectHierarchy();

        if (gO == null)
        {
            Debug.LogWarning("Selection is not a GameObject");
            return;
        }

        GameObject rootGO = PrefabUtility.GetOutermostPrefabInstanceRoot(gO);
        
        if (rootGO == null)
        {
            Debug.LogWarning(string.Format("Selected GameObject ({0}) is not part of a prefab", gO), gO);
            return;
        }

        PrefabInstanceStatus prefabInstanceStatus = PrefabUtility.GetPrefabInstanceStatus(rootGO);
        if (prefabInstanceStatus != PrefabInstanceStatus.Connected)
        {
            Debug.LogWarning(string.Format("Selected Prefab Root of {0} ({1}) has invalid status of {2}", gO, rootGO, prefabInstanceStatus), rootGO);
            return;
        }

        if (!PrefabUtility.HasPrefabInstanceAnyOverrides(rootGO, false))
        {
            Debug.LogWarning(string.Format("Selected Prefab Root of {0} ({1}) doesn't have any overrides", gO, rootGO), rootGO);
            return;
        }

        PrefabUtility.ApplyPrefabInstance(rootGO, InteractionMode.UserAction);
        AssetDatabase.SaveAssets();
        
        Debug.Log(string.Format("Changes on {0} applied to {1}", gO, rootGO), rootGO);
    }

    private static GameObject GetCurrentlySelectedObjectHierarchy() => Selection.activeGameObject;
}
于 2021-11-24T09:47:13.477 回答