Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 13 Next capture
2021 2022 2023
1 capture
13 Jun 22 - 13 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
1
Question by Simon-O · Nov 08, 2020 at 01:29 AM · loadscene-loadingscene-switchingload sceneasync

Loading screen with long-running CPU-heavy Awake()

I have a scene with lots of lightweight objects and one that takes anywhere between 10 and 45 seconds to load.

At a high level, the Awake method does...

  • Query database

  • For each result do some (fairly heavy) calculations

  • Populate a list

  • Use that list to generate game objects

Most of the time is spent in 1+2, and only the last step needs to execute on the main thread

I have another scene to display a loading screen. It has a UI panel with a shader that shows an animation.

The Loading screen starts a coroutine to switch level...

 private IEnumerator LoadNewScene() {
     AsyncOperation async = SceneManager.LoadSceneAsync("GalaxyMap", LoadSceneMode.Single);
     while (!async.isDone) {
         yield return null;
     }
     // I'm doing cleanup here when trying additive load
 }

At which point, the animation freezes for 10-45 seconds while the heavy object loads.

In an attempt to make the animation CPU-independent, it's coded as a shader using the built-in _Time property.

I assume this is because my heavy object's Awake() is running on Unity's main thread and thus is blocking updates to the shader.

If so, I can move a lot of the heavy lifting onto a background thread, but I can't work out how to release the thread back to Unity temporarily.

The Awake() method isn't async, and any attempt to create a Task and wait for it will just block the same thread.

Conversely, I could have a completion callback for when the load is done. That would allow me to release the main thread sooner, however, Unity would think my scene had finished loading prematurely and remove the loading screen.

How can I either:

  • Release control of the thrad intermittently so Unity can refresh the UI

  • Explicitly tell Unity when it should consider a scene "loaded" and ready for display

?

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

1 Reply

· Add your reply
  • Sort: 
avatar image
1

Answer by rh_galaxy · Nov 08, 2020 at 10:36 AM

You can't have Awake() or Start() that takes time, they will block until done. Instead you can use another thread, but some code that must interact with Unity must run from the main thread. Here is an example of how this can be done. Two classes involved, and a thread. Work is split up so that things needing Unity main thread interaction can be done, then continue the thread. It became rather much code, but I hope it will help. After this you can continue doing loading stuff in Update() of the second class for however many frames you need, and set Time.timeScale = 0 until all is done. Even with all of this, it may not be possible to have smooth framerate during load.

Fading to black during load is what I eventually did, but 45 sec is a long time without any progress indication, so it might be good to try as hard as you can. My project loads for about 5 sec. It is VR and relies on 90Hz or the user would notice since the view must be rendered continuously to count for the head movement, even when the contents does not move/change. If you can settle for a frame now and then this will work ok for you, without having to split the work in the main thread too much.

 GameManager:
 
 int iState = 0;
 bool bLoadDone = false;
 void Update()
 {
     //the main state machine
     switch (iState)
     {
         case 0:
             szToLoad = "GameScene"
 
             bLoadDone = false;
             StartCoroutine(LoadAsyncScene());
             iState++;
             break;
         case 1:
             //while loading level
             if (bBeginMapGeneration)
             {
                 Debug.Log("Load scene, level 90%");
                 if (!bLoadDone) bLoadDone = GameLevel.Load();
                 if (bLoadDone)
                 {
                     Debug.Log("Generate map done");
                     iState++;
                 }
             }
             break;
         case 2:
             //running game
             //...
             break;
     }
 }
 
 bool bBeginMapGeneration = false;
 string szToLoad = "";
 IEnumerator LoadAsyncScene()
 {
     //the Application loads the scene in the background as the current scene runs
     // this is good for not freezing the view... done by separating some work to a thread
     // and having the rest split in ~7ms jobs
 
     asyncLoad = SceneManager.LoadSceneAsync(szToLoad, LoadSceneMode.Single);
     asyncLoad.allowSceneActivation = false;
 
     //wait until the asynchronous scene fully loads
     while (!asyncLoad.isDone)
     {
         //scene has loaded as much as possible, the last 10% can't be multi-threaded
         if (asyncLoad.progress >= 0.9f)
         {
             bBeginMapGeneration = true;
             if (bLoadDone)
                 asyncLoad.allowSceneActivation = true;
         }
         yield return null;
     }
 }
 
 GameLevel:
 
 Thread thread;
 ManualResetEvent oEvent = new ManualResetEvent(false);
 bool bMeshReady = false;
 void LoadThread()
 {
     //part 1 of thread
     //...
 
     bMeshReady = true;
     oEvent.WaitOne();
 
     //part 2 of thread
     //...
 }
 
 int iLoadState = 0;
 public bool Load()
 {
     if (iLoadState == 0)
     {
         bMapLoaded = false;
         //...
         iLoadState++;
     }
     else if (iLoadState == 1)
     {
         //create thread for all other work that can be done
         // before needing work in main thread
         ThreadStart ts = new ThreadStart(LoadThread);
         thread = new Thread(ts);
         thread.Priority = System.Threading.ThreadPriority.Lowest;
         thread.Start();
         iLoadState++;
     }
     else if (iLoadState == 2)
     {
         if (bMeshReady)
         {
             //oMeshGen.SetGenerateMeshToUnity();
 
             bMeshReady = false;
             oEvent.Set(); //allow part 2 of thread to start
             iLoadState++;
         }
     }
     else if (iLoadState == 3)
     {
         if (!thread.IsAlive)
         {
             iLoadState = 0;
             return true;
         }
     }
     return false;
 }
Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

144 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

AsyncOperation activating immediately even with async.allowSceneActivation = false; 0 Answers

SceneManager.LoadSceneAsync freeze loading scene in editor. 0 Answers

LoadScene.Single don't close the current scene 1 Answer

How to prevent a script from running until the scene is loaded? 2 Answers

Loading Muiltiple Scenes Async 0 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges