﻿#if UNITY_EDITOR
using UnityEngine;
using UnityEditor;
using System.IO;

public class CreateAssetbundle : MonoBehaviour {


    [MenuItem("Fineness/Build AssetBundle From Select Resource")]
    static void SelectResourceAndBuildAB()
    {
        UnityEngine.Object[] selecteds = Selection.GetFiltered(typeof(UnityEngine.Object), SelectionMode.DeepAssets);
        var count = 0;
        var max = selecteds.Length;
        var fileNames = new string[max];
        var assetBundle = new AssetBundleBuild();
        Debug.Log("即将打包的文件路径队列：");
        for (var i = 0; i < max; i++)
        {
            var target = selecteds[i];
            string assetPath = AssetDatabase.GetAssetPath(target);
            var fileName = assetPath;
            assetPath = assetPath.Replace("Assets/", "");
            var fileInfo = new FileInfo(assetPath);
            if ((fileName.IndexOf('.') != -1) &&
                (fileInfo.Extension != "cs") &&
                (fileInfo.Extension != "meta"))
            {
                fileNames[i] = fileName;
                count++;
                Debug.Log(i + " >> " + fileNames[i]);
            }
        }
        if (count > 0)
        {
            var activer = Selection.activeObject;
            if (activer == null)
            {
                Debug.Log(" ╮(╯▽╰)╭ 缺少被选中的激活物件，请选择后重试...");
                return;
            }
            assetBundle.assetBundleName = activer.name;
            assetBundle.assetNames = fileNames;
            var outputFileName = Application.streamingAssetsPath + "/AB" + assetBundle.assetBundleName;
            if (!Directory.Exists(outputFileName))
                Directory.CreateDirectory(outputFileName);
            var options = BuildAssetBundleOptions.None;
            var path = "Assets" + outputFileName.Replace(Application.dataPath, "");
            BuildPipeline.BuildAssetBundles(path, new[] { assetBundle }, options, EditorUserBuildSettings.activeBuildTarget);
            AssetDatabase.Refresh();
            Debug.Log(" ♪(^∇^*) 尊敬的主人，打包已完成，资源存放路径：" + path);
        }
        else
            Debug.Log("所选文件中没有可打包的资源");
    }
}


//获取打包的平台
public class PlatformPath
{
    /// <summary>
    /// 获取打包的平台，根据平台设置打包的文件夹名称
    /// </summary>
    /// <param name="target"></param>
    /// <returns></returns>
    public static string GetPlatformFolder(BuildTarget target)
    {
        switch (target)
        {
            case BuildTarget.Android:
                return "Android";
            case BuildTarget.iOS:
                return "IOS";
            //case BuildTarget.WebPlayer:
            //    return "WebPlayer";
            case BuildTarget.StandaloneWindows:
            case BuildTarget.StandaloneWindows64:
                return "Windows";
            case BuildTarget.StandaloneOSXIntel:
            case BuildTarget.StandaloneOSXIntel64:
            case BuildTarget.StandaloneOSXUniversal:
                return "OSX";
            default: return null;
        }
    }
}
#endif
