Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Question Scene Loading Optimization

Discussion in 'Editor & General Support' started by Lunarthewolf, Apr 27, 2023.

  1. Lunarthewolf

    Lunarthewolf

    Joined:
    Feb 10, 2019
    Posts:
    10
    Does Unity do any smart unloading by default? Let's say I have an asset in Scene A that is also used in Scene B. When I call LoadScene("Scene B"), will the shared asset be unloaded and then reloaded? Or is Unity set up to know it will still need the asset for Scene B, and hold onto it?
     
  2. DevDunk

    DevDunk

    Joined:
    Feb 13, 2020
    Posts:
    4,214
    Depends how the object is setup as far as I know (don't know the full inner workings).
    If a texture is in memory and used twice, it will probably only keep 1 copy if 2 scenes are active and use it (I suggest to use async scene loading if you want a smooth transition).
    But if a script in both scenes has data in it which is not a seperate asset, it will have 2 copies of course.

    I am guessing that just using loadScene reloads everything, since it will fully unload 1 scene. Otherwise there would need to be a pass that compares every data segment in 1 scene to the other, killing performance

    If you want to make sure check out the memory profiler maybe?
     
  3. rdjadu

    rdjadu

    Joined:
    May 9, 2022
    Posts:
    99
    There actually won't be two copies. If an object has already been loaded from disk, Unity's "persistence manager" will, when the object is requested, just produce the existing asset instance.

    Question is whether Unity runs its "asset garbage collection"* (which is actually separate from C# heap GC but does use the same scanner to determine liveness; meaning Unity actually has two separate GCs in a way) *in-between* unloading A and loading B. Don't remember whether it does or not. If it does, assets from scene A would get unloaded before assets from scene B get loaded. So, a shared texture would be gone. If it does not do the pass in-between, a shared texture would stay loaded.

    My guess would be there's no asset GC pass in-between the loads and thus shared assets will stay resident. But that's a guess :)

    *The one you can trigger manually with
    Resources.UnloadUnusedAssets
    .
     
    DevDunk likes this.