Version: 2021.3

PrefabUtility.LoadPrefabContents

切换到手册
public static GameObject LoadPrefabContents (string assetPath);

参数

assetPath 要加载其内容的预制件资源的路径。

返回

GameObject 已加载内容的根。

描述

将给定路径上的预制件资源加载到孤立场景中,并返回预制件的根游戏对象。

可以使用它来获取预制件的内容并直接予以修改,而不是遍历预制件的实例。这可用于批处理操作。

Once you have modified the Prefab you have to write it back using SaveAsPrefabAsset and then call UnloadPrefabContents to release the Prefab and isolated Scene from memory.

See Also: EditPrefabContentsScope.

using UnityEngine;
using UnityEditor;

public class Example { [MenuItem("Examples/Add BoxCollider to Prefab Asset")] static void AddBoxColliderToPrefab() { // Get the Prefab Asset root GameObject and its asset path. GameObject assetRoot = Selection.activeObject as GameObject; string assetPath = AssetDatabase.GetAssetPath(assetRoot);

// Load the contents of the Prefab Asset. GameObject contentsRoot = PrefabUtility.LoadPrefabContents(assetPath);

// Modify Prefab contents. contentsRoot.AddComponent<BoxCollider>();

// Save contents back to Prefab Asset and unload contents. PrefabUtility.SaveAsPrefabAsset(contentsRoot, assetPath); PrefabUtility.UnloadPrefabContents(contentsRoot); }

[MenuItem("Examples/Add BoxCollider to Prefab Asset", true)] static bool ValidateAddBoxColliderToPrefab() { GameObject go = Selection.activeObject as GameObject; if (go == null) return false;

return PrefabUtility.IsPartOfPrefabAsset(go); } }
Copyright © 2023 Unity Technologies
优美缔软件(上海)有限公司 版权所有
"Unity"、Unity 徽标及其他 Unity 商标是 Unity Technologies 或其附属机构在美国及其他地区的商标或注册商标。其他名称或品牌是其各自所有者的商标。
公安部备案号:
31010902002961