-
-
Save arcueid-dev/ef58bc3d5f5f2897c1f77c5343d71a5e 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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /** | |
| * 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