Unity一键制作预制体Prefab一键修改Prefab属性

1.适用于制作多个预制体(一个模型文件下面几百个子物体,都需要制作成预制体,这一个一个拖不是要炸裂)

模型资源如下图
![请添加图片描述](https://img-blog.csdnimg.cn/6393717aa80d45d29a6bbffed87496b0.png
Unity一键制作预制体Prefab一键修改Prefab属性_第1张图片

2.模型先放到Resources文件夹下面方便读取,制作完预制体可以给他拖到其他文件夹

模型文件结构如下图(经测试放模型的文件夹名字要和模型名字一致,不然找不到,你也可以修改代码测试其他方法)
Unity一键制作预制体Prefab一键修改Prefab属性_第2张图片

3.下面是编辑器脚本

using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEngine;
/// 
/// 编辑器脚本
/// 

public class CreationPrefab : EditorWindow
{
    [MenuItem("Tools/一键生成Prefab")]
    public static void CreatePrefabWindow()
    {
        EditorWindow window = EditorWindow.GetWindowWithRect(typeof(CreationPrefab), new Rect(Screen.width / 3, Screen.height / 3, 800, 500), true, "CreationPrefab");
        window.Show();
    }
    //保存prefab的路径
    private static string toSavePrefabPath = "Assets/Prefabs/新模型库/机柜内设备";


    private void OnGUI()
    {

        EditorGUILayout.LabelField("预制体保存路径::", toSavePrefabPath, GUILayout.Width(110));
        toSavePrefabPath = EditorGUILayout.TextArea(toSavePrefabPath, GUILayout.Width(250));

        if (GUILayout.Button("转换预制体", GUILayout.Width(260)))
        {
            ToPrefab();
        }

        if (GUILayout.Button("修改预制体", GUILayout.Width(260)))
        {          
            ModifyPrefab(toSavePrefabPath);
        }

    }
    private void ToPrefab()
    {
        string path = "Assets/Resources";
        string[] allFolder1 = GetAllFolder(path);
        if (allFolder1 == null)
            return;
        //循环次数取决于 ,源文件的目录结构 ,此处为 4 级结构  
        //也就是Resources下面4级文件夹,到达模型文件夹  一级一个for循环
        for (int i = 0; i < allFolder1.Length; i++)
        {
            string path2 = $"{path}/{allFolder1[i]}";
            string[] allFolder2 = GetAllFolder(path2);
            if (allFolder2 == null)
            {
                return;
            }
            for (int j = 0; j < allFolder2.Length; j++)
            {
                string path3 = $"{path2}/{allFolder2[j]}";
                string[] allFolder3 = GetAllFolder(path3);
                if (allFolder3 == null)
                    return;
                for (int k = 0; k < allFolder3.Length; k++)
                {

                    string path4 = $"{path3}/{allFolder3[k]}";
                    string[] allFolder4 = GetAllFolder(path4);
                    Debug.Log($"编号:{k}     {allFolder3[k]}文件下有        {allFolder4.Length}       个文件夹!");
                    if (allFolder4 == null)
                        return;

                    if (!Directory.Exists(toSavePrefabPath))
                    {
                        Directory.CreateDirectory(toSavePrefabPath);
                    }

                    for (int l = 0; l < allFolder4.Length; l++)
                    {
                        string speedTree = $"{path4}/{allFolder4[l]}/{allFolder4[l]}";
                        string[] strs = Regex.Split(speedTree, path + "/", RegexOptions.IgnoreCase);
                        GameObject go = Instantiate(GetFileObj(strs[1]));
                        go.name = go.name.Replace("(Clone)", string.Empty);
                        //给预制体添加脚本,修改属性
                        //go.transform.tag = "Model";
                        //if (go.GetComponent() == null)
                        //    go.AddComponent();

                        //if (go.GetComponent() == null)
                        //    go.AddComponent();

                        //go.GetComponent().isKinematic = true;

                        string modeName = allFolder4[l].Split('_')[0];


                        for (int p = 0; p < go.transform.childCount; p++)
                        {
                            PrefabUtility.SaveAsPrefabAsset(go.transform.GetChild(p).gameObject, $"{toSavePrefabPath}/{go.transform.GetChild(p).name}.prefab");


                        }

                        DestroyImmediate(go);


                    }
                    AssetDatabase.Refresh();
                }
            }

        }

    }

    /// 
    /// 获取路径下的 Obj
    /// 
    /// 
    /// 
    private GameObject GetFileObj(string path)
    {
        GameObject go = Resources.Load<GameObject>(path);
        if (go != null)
        {
            return go;
        }
        else
        {
            Debug.Log(path);
            return null;
        }

    }
    /// 
    /// 获取路径下的所有文件夹
    /// 
    /// 
    /// 
    private string[] GetAllFolder(string path)
    {
        try
        {

            string[] dirs = Directory.GetDirectories(path, "*");
            string[] folderName = new string[dirs.Length];
            for (int i = 0; i < dirs.Length; i++)
            {
                string file = dirs[i].Split('\\')[1];
                folderName[i] = file;
            }
            return folderName;
        }
        catch (System.Exception)
        {

            return null;
        }


    }

    /// 
    /// 修改预制体
    /// 
    /// 
    private void ModifyPrefab(string path)
    {
       
        //获取文件下所有预制体文件
        DirectoryInfo info = new DirectoryInfo(path);
        FileInfo[] fileInfos = info.GetFiles("*.prefab");       
        List<GameObject> prefabs = new List<GameObject>();
        foreach (var item in fileInfos)
        {
            string paths = $"{path}/{item.Name}";
            GameObject prefab = AssetDatabase.LoadAssetAtPath(paths, typeof(GameObject)) as GameObject;
            prefabs.Add(prefab);
        }
        Debug.Log("执行么" + prefabs.Count);
        //修改属性
        for (int i = 0; i < prefabs.Count; i++)
        {           
            //修改预制体的position和旋转角度
            if (prefabs[i].GetComponent<Transform>() != null)
            {
                prefabs[i].GetComponent<Transform>().position = Vector3.zero;
                prefabs[i].GetComponent<Transform>().rotation = Quaternion.Euler(Vector3.zero);
            }
            //其他属性请自行添加即可
            //if (prefabs[i].GetComponent() != null)
            //{
            //    prefabs[i].GetComponent().isKinematic = false;
            //    PrefabUtility.SavePrefabAsset(prefabs[i]);
            //}

        }
        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();
    }
}

两个功能一个生成预制体,一个修改预制体的坐标和角度为0

功能显示位置如下图
请添加图片描述

编辑器脚本需放到Editor文件夹下面

你可能感兴趣的:(unity,游戏引擎,编辑器)