FileDownloadWindow.cs

December 26, 2018 ยท View on GitHub

using System; using System.ComponentModel; using System.IO; using System.Net; using UnityEditor; using UnityEngine;

public sealed class FileDownloadWindow : EditorWindow { private string m_address ; private UnityEngine.Object m_folder ; private bool m_isDownloading ;

[MenuItem( "Window/File Download Window" )]
private static void Init()
{
    var win = GetWindow<FileDownloadWindow>();
    win.minSize = win.maxSize = new Vector2( 320, 80 );
}

private void OnGUI()
{
    GUI.enabled = !m_isDownloading;

    EditorGUIUtility.labelWidth = 50;

    m_address = EditorGUILayout.TextField( "URL", m_address );

    EditorGUI.BeginChangeCheck();

    var folder = EditorGUILayout.ObjectField( "Folder", m_folder, typeof( UnityEngine.Object ), false );

    if ( EditorGUI.EndChangeCheck() )
    {
        if ( folder != null )
        {
            var path = AssetDatabase.GetAssetPath( folder );
            var attr = File.GetAttributes( path );

            if ( ( attr & FileAttributes.Directory ) != 0 )
            {
                m_folder = folder;
            }
        }
        else
        {
            m_folder = null;
        }
    }

    EditorGUIUtility.labelWidth = 0;

    GUI.enabled = !m_isDownloading && !string.IsNullOrEmpty( m_address ) && m_folder != null;

    if ( GUILayout.Button( "Download" ) )
    {
        Download();
    }

    GUI.enabled = true;
}

private void Download()
{
    var wc          = new WebClient();
    var address     = new Uri( m_address );
    var filename    = Path.GetFileName( m_address );
    var directory   = AssetDatabase.GetAssetPath( m_folder );
    var path        = directory + "/" + filename;

    wc.DownloadProgressChanged  += OnChanged;
    wc.DownloadFileCompleted    += OnCompleted;

    wc.DownloadFileAsync( address, path );

    m_isDownloading = true;
}

private void OnChanged( object sender, DownloadProgressChangedEventArgs e )
{
    var progress    = e.ProgressPercentage / 100f;
    var cancel      = !EditorUtility.DisplayCancelableProgressBar
    (
        title       : "FileDownloadWindow",
        info        : m_address,
        progress    : progress
    );

    if ( !cancel ) return;

    var wc = sender as WebClient;
    wc.CancelAsync();
}

private void OnCompleted( object sender, AsyncCompletedEventArgs e )
{
    EditorUtility.ClearProgressBar();
    AssetDatabase.Refresh();

    m_isDownloading = false;
}

}