Version: 2022.1

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