用脚本生成 Prefab

    [MenuItem("Tools/创建 Roles Prefab")]
    static void Create()
    {
        string folderName = "Assets/Res/Sprites/Roles/";
        DirectoryInfo folder = new DirectoryInfo(folderName);
        FileInfo[] files = folder.GetFiles();
        int success = 0;
        foreach (FileInfo f in files)
        {
            success++;
            if (f.Extension.ToLower() == ".png")
            {
                DoCreatePrefab(f.FullName.Replace("\\", "/").Replace(Application.dataPath, "Assets"), f.Name.Substring(0, f.Name.Length - 4));
                EditorUtility.DisplayProgressBar("创建 Roles Prefab", f.Name, success / 1f / files.Length);
                // if (success >= 1) break;
            }
        }
        EditorUtility.ClearProgressBar();
        AssetDatabase.Refresh();
    }

    static void DoCreatePrefab(string file, string filename)
    {
        string prefabPath = "Assets/Res/Prefabs/NPC/" + filename + ".prefab";
        if (File.Exists(prefabPath)) return;
        Debug.Log(prefabPath);

        string clonePrefabPath = "Assets/Res/Prefabs/NPC/Base.prefab";
        GameObject prefabRef = (GameObject)AssetDatabase.LoadMainAssetAtPath(clonePrefabPath);
        GameObject prefabObj = (GameObject)PrefabUtility.InstantiatePrefab(prefabRef);

        var script = prefabObj.GetComponent();
        script.skin = filename;
        PrefabUtility.UnpackPrefabInstance(prefabObj, PrefabUnpackMode.OutermostRoot, InteractionMode.AutomatedAction);

        var spr = prefabObj.GetComponent();
        var assets = AssetDatabase.LoadAllAssetsAtPath(file);
        spr.sprite = assets[1] as Sprite;

        GameObject obj = PrefabUtility.SaveAsPrefabAsset(prefabObj, prefabPath);

        GameObject.DestroyImmediate(prefabObj);
    }

你可能感兴趣的:(用脚本生成 Prefab)