Search Unity

Lag spikes due to Garbage Collection in SceneManager?

Discussion in 'Scripting' started by Terpal, Oct 5, 2018.

  1. Terpal

    Terpal

    Joined:
    Apr 5, 2018
    Posts:
    5
    Hi,

    I'm running into some pretty bad lag spikes (200 FPS down to 15 FPS) that occurs every so often at the beginning of my scene. Here's the profiler with deep profiling:

    upload_2018-10-5_22-36-53.png

    I appears some sort of garbage collection is happening in AddMoney.Start(), related to the SceneManager. Here's the relevant code from AddMoney:

    Code (CSharp):
    1. void Start()
    2. {
    3.     SceneManager.sceneUnloaded += OnChangeScene;
    4. }
    and

    Code (CSharp):
    1. public void OnChangeScene(Scene current)
    2. {
    3.     // Reset subscriptions.
    4.     addMoneyEvent = null;
    5. }
    where addMoneyEvent is a field declared as:

    Code (CSharp):
    1. public static event Action<float> addMoneyEvent;
    I can't figure out why this lag spike is happening and what to do about it. It's strange as well because I have other classes subscribing to SceneManager.sceneUnloaded too, but none of them are causing these huge lag spikes.

    The 308 calls to AddMoney.Start() and 525294 calls to Delegate.Clone() seem extremely odd too, and I can't quite figure out what's going on.

    It's worth noting the lag spikes stop after a few dozen seconds.

    Any ideas? Let me know if I can supply any other info.
     
    Last edited: Oct 5, 2018
  2. Terpal

    Terpal

    Joined:
    Apr 5, 2018
    Posts:
    5
    Doh, I've realized the silly mistake.
    AddMoney is a script that's added on to many objects, so each object is individually subscribing, which is pretty costly. I've fixed it with a simple static "initialized" bool that ensures it subscribes only once.

    Sorry for wasting anyone's time!