Search Unity

Application LoadLevel and delegates

Discussion in 'Editor & General Support' started by jbecana, Feb 1, 2015.

  1. jbecana

    jbecana

    Joined:
    Feb 14, 2012
    Posts:
    22
    I'm not an expert so before considering this is as a bug, I want to know your opinion. I supposed that loading a level using Application.LoadLevel would start a new "fresh" scene. Wrong. As I read in the docs, this action will destroy all scene objects, but that is not what I found. In my case I had a gameObject subscribed to some events on Awake. I never removed this subscription because this object is supposed to exists throughout the level. But when I ran an Application.LoadLevel from a restart menu option my application misbehaved. After the level started again I surprisingly found the event sender object was sending the events to an object instance form the old scene. whose internal variables were referencing destroyed objects, and caused the application to fail. Using MonoDevelop I could see the receiver object was correctly initialized, but the delegate was executing a method from another instance. I cannot see other interpretation besides my event sender was not destroyed at all, but as I said, I'm not an expert. As a workaround I have included all event add/remove sentences in OnEnable/OnDisable blocks as OnDisable is always executed when reloading the level, and all is fine. Any thoughts?
     
  2. lzt120

    lzt120

    Joined:
    Apr 13, 2010
    Posts:
    93
    DontDestroyOnLoad may help
     
  3. jbecana

    jbecana

    Joined:
    Feb 14, 2012
    Posts:
    22
    Thanks for your reply. I think this is the opposite, my script object should be deleted and it is not, at least this is what I can suppose after some debugging. I wanted to know if using delegates and events could cause any object to persist in the scene once you reload it.
     
  4. lzt120

    lzt120

    Joined:
    Apr 13, 2010
    Posts:
    93
    You can has one script in your scene and in Awake you can delete all the objects you want