1 [ExecuteInEditMode] 2 [MenuItem("Tools/RecordPoint Add Flame")] 3 private static void RecordPointAddFlame() 4 { 5 GameObject twoSphere = AssetDatabase.LoadAssetAtPath("Assets/Resources/Prefabs/TwoSphere.prefab", typeof(GameObject)) as GameObject; 6 7 string[] ids = AssetDatabase.FindAssets("t:Prefab", new string[] { "Assets/Resources/Prefabs" }); 8 for (int i = 0; i < ids.Length; i++) 9 { 10 string path = AssetDatabase.GUIDToAssetPath(ids[i]); 11 Debug.Log(path); 12 if (!path.Contains("TwoCube")) 13 { 14 continue; 15 } 16 GameObject originTwoCube = AssetDatabase.LoadAssetAtPath(path, typeof(GameObject)) as GameObject; 17 GameObject twoCube = PrefabUtility.InstantiatePrefab(originTwoCube) as GameObject; 18 19 foreach (Transform item in twoCube.transform) 20 { 21 if (item.FindChild("TwoSphere") == null) 22 { 23 GameObject ts = PrefabUtility.InstantiatePrefab(twoSphere) as GameObject; 24 ts.transform.parent = item; 25 } 26 } 27 28 var newprefab = PrefabUtility.CreateEmptyPrefab("Assets/Resources/Prefabs/TwoCube.prefab"); 29 PrefabUtility.ReplacePrefab(twoCube, newprefab, ReplacePrefabOptions.Default); 30 } 31 32 AssetDatabase.SaveAssets(); 33 Debug.Log("Done"); 34 }
這段代碼的功能是在TwoCube這個prefab的兩個子對象cube上掛一個名為TwoSphere的prefab。如圖
最終結果如下:
代碼中為什么要使用PrefabUtility.InstantiatePrefab和PrefabUtility.ReplacePrefab,這是因為上述例子有一點比較特殊的地方,就是是一個prefab中嵌入另一個prefab。如果單純的只是操作一個prefab是沒有必要這樣做的。