assetPath | 要加载其内容的预制件资产的路径。 |
GameObject 已加载内容的根目录。
将位于给定路径下的预制件资产加载到隔离场景中,并返回预制件的根目录 GameObject。
你可以使用此方法来获取预制件的内容并直接修改它,而不必经过预制件的实例。这对批量操作非常有用。
修改完预制件后,你必须使用 SaveAsPrefabAsset 将其重新写入,然后调用 UnloadPrefabContents 来从内存中释放预制件和隔离场景。
额外资源: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); } }