Skip to content

Instantly share code, notes, and snippets.

@luke161
Last active June 27, 2024 02:53
Show Gist options
  • Save luke161/a251b01c00f58d65a252812be8dce670 to your computer and use it in GitHub Desktop.
Save luke161/a251b01c00f58d65a252812be8dce670 to your computer and use it in GitHub Desktop.
Custom DownloadHandler for UnityWebRequest to stream contents into a file. Useful for preloading AssetBundles without them automatically being uncompressed and loaded into memory.
/**
* DownloadHandlerFile.cs
* Author: Luke Holland (http://lukeholland.me/)
*/
using UnityEngine;
using UnityEngine.Networking;
using System.IO;
public class DownloadHandlerFile : DownloadHandlerScript
{
public int contentLength { get { return _received>_contentLength ? _received : _contentLength; } }
private int _contentLength;
private int _received;
private FileStream _stream;
public DownloadHandlerFile(string localFilePath, int bufferSize = 4096, FileShare fileShare = FileShare.ReadWrite) : base(new byte[bufferSize])
{
string directory = Path.GetDirectoryName(localFilePath);
if(!Directory.Exists(directory)) Directory.CreateDirectory(directory);
_contentLength = -1;
_received = 0;
_stream = new FileStream(localFilePath,FileMode.OpenOrCreate, FileAccess.Write, fileShare, bufferSize);
}
protected override float GetProgress ()
{
return contentLength<=0 ? 0 : Mathf.Clamp01((float)_received/(float)contentLength);
}
protected override void ReceiveContentLength (int contentLength)
{
_contentLength = contentLength;
}
protected override bool ReceiveData (byte[] data, int dataLength)
{
if(data==null || data.Length==0) return false;
_received += dataLength;
_stream.Write(data,0,dataLength);
return true;
}
protected override void CompleteContent ()
{
CloseStream();
}
public new void Dispose()
{
CloseStream();
base.Dispose();
}
private void CloseStream()
{
if(_stream!=null){
_stream.Dispose();
_stream = null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment