首页 > 技术文章 > Unity编辑器工具_一键生成/修改预制体

guangzhiruijie 2022-01-20 11:02 原文

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.IO;

public class Tool
{
    static Dictionary<int, Table_item> items_ID = TableManager.Getitem();
    static Dictionary<string, Table_item> items_Name = new Dictionary<string, Table_item>();

    [MenuItem("Menu/一键导入道具信息", false, 1)]
    public static void 一键导入道具信息()
    {
        //---------------------表格初始化,并读取到字典中---------------------------//
        //此处使用的自己的文件读取方式,可以按各自的读取方式进行修改
        TableManager.Initialize();
        items_ID = TableManager.Getitem();
        items_Name.Clear();
        foreach (var item in items_ID)
        {
            items_Name.Add(item.Value.EnName, item.Value);
        }

        //---------------------创建文件夹和预制体(一定要优先创建,之后好做关联)---------------------------//
        foreach (var item in items_Name)
        {
            string path = "Assets/Resources/" + item.Value.FileName;
            string filePath = path + "/" + item.Value.EnName + ".Prefab";

            //判断预制体所在的文件夹是否存在,若不存在则创建
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            //当前预制体
            GameObject Target = AssetDatabase.LoadAssetAtPath(filePath, typeof(GameObject)) as GameObject;
                    //预制体不存在
            if (!Target)
            {
                GameObject newGameObject = new GameObject();
                
                //新建预制体的处理,例如添加脚本,数据初始化,可以才是用switch来分别对不同的预制体添加不同的脚本

                PrefabUtility.SaveAsPrefabAsset(newGameObject, filePath);
                GameObject.DestroyImmediate(newGameObject);
            }
                   else    
                   {
                       Target = PrefabUtility.InstantiatePrefab(Target) as GameObject;

                        //此处进行预制体的修改,依旧使用Switch来获取对应脚本来进行数据替换
                        
                        PrefabUtility.SaveAsPrefabAsset(Target, filePath);
                        GameObject.DestroyImmediate(Target);
                   }
        }
        //保存修改
        AssetDatabase.SaveAssets();
        AssetDatabase.Refresh();
    }
 
  

  

推荐阅读