- Home /
LoadSceneAsync freeze workaround
This is insane and totally like nothing else, but to avoid a 6 second freeze when the file has never been loaded (not in any cache), I added a thread that preloads the resource file (700MB) to the cache during the time the player spends in the menu before this will be accessed by LoadSceneAsync next thing. So much for async.
Why does LoadSceneAsync on a scene not yet activated cause any freeze at all (I also use the new incremental GC to avoid any such hiccups)? I'm using a high end Windows computer.
What do you think of my approach and why does it avoid the freeze during the async load?
As a side note I do not care for memory usage (it can be done better), only to eliminate freezes at all cost.
//includes
using UnityEngine.SceneManagement;
using System.IO;
using System.Threading;
//the thread
byte[] preLoadBytes;
string preLoadDataPath;
Thread preLoadThread;
void PreLoadAssetsToCache()
{
preLoadBytes = File.ReadAllBytes(preLoadDataPath + "/sharedassets1.assets.resS");
preLoadBytes = null;
}
//at first
UnityEngine.Application.backgroundLoadingPriority = UnityEngine.ThreadPriority.BelowNormal;
Thread.CurrentThread.Priority = System.Threading.ThreadPriority.AboveNormal;
//after app start, in menu, load the file to cache in a low prio thread
preLoadDataPath = UnityEngine.Application.dataPath;
ThreadStart ts = new ThreadStart(PreLoadAssetsToCache);
preLoadThread = new Thread(ts);
preLoadThread.Priority = System.Threading.ThreadPriority.Lowest;
preLoadThread.Start();
//later this happens and causes the freeze of the main thread (and any frame updates)
asyncLoad = SceneManager.LoadSceneAsync(szToLoad, LoadSceneMode.Single);
asyncLoad.allowSceneActivation = false;
//later proper scene activation and other init (called integration to main thread)
Note that there are other hiccups later because of other things, this is strictly about a huge frame delay really when running the previously release built application first time after a reboot.
Other things one could ask; Is this a reasonable workaround or is LoadSceneAsync severely broken?