Unity3D Editor模式下批量修改prefab
技术文库图文教程技术文章3D建模
显示全部 9
199 3
实名

通过了实名认证的内容创造者

发布于 2024-10-20 21:46:29

您需要 登录 才可以下载或查看,没有账号?注册

x
本帖最后由 雾切酱 于 2018-10-22 11:54 编辑

Unity3D Editor模式下批量修改prefab https://www.bbsmax.com/A/l1dyYl40de/

最经遇到一个需要批量修改已经做好的prefab的问题,
查了一些资料最终实现了但是还是不够完美,
通过学习也发现unity的编辑器功能还是非常强大的。
废话不多说直接上代码:

  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.         string[] ids = AssetDatabase.FindAssets("t:Prefab", new string[] { "Assets/Resources/Prefabs" });
  7.         for (int i = 0; i < ids.Length; i++)
  8.         {
  9.             string path = AssetDatabase.GUIDToAssetPath(ids[i]);
  10.             Debug.Log(path);
  11.             if (!path.Contains("TwoCube"))
  12.             {
  13.                 continue;
  14.             }
  15.             GameObject originTwoCube = AssetDatabase.LoadAssetAtPath(path, typeof(GameObject)) as GameObject;
  16.             GameObject twoCube = PrefabUtility.InstantiatePrefab(originTwoCube) as GameObject;

  17.             foreach (Transform item in twoCube.transform)
  18.             {
  19.                 if (item.FindChild("TwoSphere") == null)
  20.                 {
  21.                     GameObject ts = PrefabUtility.InstantiatePrefab(twoSphere) as GameObject;
  22.                     ts.transform.parent = item;
  23.                 }
  24.             }

  25.             var newprefab = PrefabUtility.CreateEmptyPrefab("Assets/Resources/Prefabs/TwoCube.prefab");
  26.             PrefabUtility.ReplacePrefab(twoCube, newprefab, ReplacePrefabOptions.Default);
  27.         }

  28.         AssetDatabase.SaveAssets();
  29.         Debug.Log("Done");
  30.     }
点击此处复制文本


这段代码的功能是在TwoCube这个prefab的两个子对象cube上挂一个名为TwoSphere的prefab。如图


630025bcd29861a6f7.png


最终结果如下:



519785bcd29bc8d1f4.png


代码中为什么要使用PrefabUtility.InstantiatePrefab和PrefabUtility.ReplacePrefab,

这是因为上述例子有一点比较特殊的地方,

就是是一个prefab中嵌入另一个prefab。

如果单纯的只是操作一个prefab是没有必要这样做的。


使用道具 <
红烧大白菜  发表于 2018-10-23 17:28:04  
2#
编程方面完全不懂。
回复 收起回复
使用道具
胖-哒  发表于 2018-10-23 19:13:16  
3#
感谢分享~~~~
回复 收起回复
使用道具
fyt_2017  发表于 2018-10-25 11:22:28  
4#
学习了,非常感谢
回复 收起回复
使用道具
您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表