Unity3D Editor模式下批量修改prefab


轉載地址:http://www.cnblogs.com/klkucan/p/4934518.html#undefined
 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是沒有必要這樣做的。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM