[Unity]大文件的下载

2020/08 31 15:08

在Android机上测试更新包文件下载,放了一个800M的包体,下载时,AppCrash,Logcat上显示:

08-31 12:05:02.641 11195 11227 E Unity   : Could not allocate memory: System out of memory!
08-31 12:05:02.641 11195 11227 E Unity   : Trying to allocate: 902692864B with 16 alignment. MemoryLabel: WebRequest
08-31 12:05:02.641 11195 11227 E Unity   : Allocation happened at: Line:75 in
08-31 12:05:02.641 11195 11227 E Unity   : Memory overview
08-31 12:05:02.641 11195 11227 E Unity   :
08-31 12:05:02.641 11195 11227 E Unity   : [ ALLOC_DEFAULT ] used: 24546420B | peak: 475860184B | reserved: 25104355B
08-31 12:05:02.641 11195 11227 E Unity   : [ ALLOC_TEMP_JOB ] used: 2980873B | peak: 0B | reserved: 7340032B
08-31 12:05:02.641 11195 11227 E Unity   : [ ALLOC_TEMP_BACKGROUND_JOB ] used: 0B | peak: 0B | reserved: 1048576B
08-31 12:05:02.641 11195 11227 E Unity   : [ ALLOC_GAMEOBJECT ] used: 834054B | peak: 835462B | reserved: 838310B
08-31 12:05:02.641 11195 11227 E Unity   : [ ALLOC_GFX ] used: 147076B | peak: 3899375B | reserved: 148311B
08-31 12:05:02.641 11195 11227 E Unity   : [ ALLOC_TEMP_THREAD ] used: 0B | peak: 0B | reserved: 3342336B
0

推测是由于UnityWebRequest申请了过大的内存

查阅官方文档:

There are several types of DownloadHandlers:
DownloadHandlerBuffer is used for simple data storage.
DownloadHandlerFile is used for downloading and saving file to disk with low memory footprint.
DownloadHandlerTexture is used for downloading images.
DownloadHandlerAssetBundle is used for fetching AssetBundles.
DownloadHandlerAudioClip is used for downloading audio files.
DownloadHandlerMovieTexture is used for downloading video files. It is recommended that you use VideoPlayer for video download and movie playback since MovieTexture is deprecated.
DownloadHandlerScript is a special class. On its own, it does nothing. However, this class can be inherited by a user-defined class. This class receives callbacks from the UnityWebRequest system, which can then be used to perform completely custom handling of data as it arrives from the network.

所以改写大文件下载

var fileHandler = new DownloadHandlerFile(saveLocalFilename);
fileHandler.removeFileOnAbort = true;

UnityWebRequest request = UnityWebRequest.Get(url);
request.downloadHandler = fileHandler;
request.timeout = requestTimeout;
request.SendWebRequest();