雾切酱 发表于 2024-10-20 21:46:29

Unity3D Editor模式下批量修改prefab

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

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

   
    private static void RecordPointAddFlame()
    {
      GameObject twoSphere = AssetDatabase.LoadAssetAtPath("Assets/Resources/Prefabs/TwoSphere.prefab", typeof(GameObject)) as GameObject;

      string[] ids = AssetDatabase.FindAssets("t:Prefab", new string[] { "Assets/Resources/Prefabs" });
      for (int i = 0; i < ids.Length; i++)
      {
            string path = AssetDatabase.GUIDToAssetPath(ids);
            Debug.Log(path);
            if (!path.Contains("TwoCube"))
            {
                continue;
            }
            GameObject originTwoCube = AssetDatabase.LoadAssetAtPath(path, typeof(GameObject)) as GameObject;
            GameObject twoCube = PrefabUtility.InstantiatePrefab(originTwoCube) as GameObject;

            foreach (Transform item in twoCube.transform)
            {
                if (item.FindChild("TwoSphere") == null)
                {
                  GameObject ts = PrefabUtility.InstantiatePrefab(twoSphere) as GameObject;
                  ts.transform.parent = item;
                }
            }

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

      AssetDatabase.SaveAssets();
      Debug.Log("Done");
    }


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



最终结果如下:




代码中为什么要使用PrefabUtility.InstantiatePrefab和PrefabUtility.ReplacePrefab,
这是因为上述例子有一点比较特殊的地方,
就是是一个prefab中嵌入另一个prefab。
如果单纯的只是操作一个prefab是没有必要这样做的。


红烧大白菜 发表于 2018-10-23 17:28:04

编程方面完全不懂。

胖-哒 发表于 2018-10-23 19:13:16

感谢分享~~~~

fyt_2017 发表于 2018-10-25 11:22:28

学习了,非常感谢
页: [1]
查看完整版本: Unity3D Editor模式下批量修改prefab