Search Unity

Does Unity recover from a null ref exception after loading a new scene?

Discussion in 'Scripting' started by brianasu, Sep 2, 2014.

  1. brianasu

    brianasu

    Joined:
    Mar 9, 2010
    Posts:
    369
    I was curious what happens when a null ref exception occurs in web and standalone then you load a new scene? Does Unity recover from it?
     
  2. Glockenbeat

    Glockenbeat

    Joined:
    Apr 24, 2012
    Posts:
    669
    What exactly do you mean with "recovering"?
     
  3. brianasu

    brianasu

    Joined:
    Mar 9, 2010
    Posts:
    369
    Well I guess usually if a null ref exception is thrown it causes most of following script excutions to fail. I guess one scenario is you have some clean up function when the scene exits and it causes a some kind of exception. When the scene loads to the next screen is the vm stuff cleared.
     
  4. smitchell

    smitchell

    Joined:
    Mar 12, 2012
    Posts:
    702
    you shouldn't have a null ref exception and let the game run.. that's really not a good idea.. Why is it being thrown?
     
  5. Glockenbeat

    Glockenbeat

    Joined:
    Apr 24, 2012
    Posts:
    669
    Usually yes, but it also depends.
    In general all objects are set to its original state on scene load as defined in the editor. Then Awake() and finally Start() jumps in and the game does its work.
    However some objects may survive scene loads when they are set to DontDestroyOnLoad() - these objects will not reset and only do stuff defined in OnLevelWasLoaded(int i):
    http://docs.unity3d.com/ScriptReference/MonoBehaviour.OnLevelWasLoaded.html

    However, NullRefs are not errors for nothing. And errors should be dealt with in an appropriate manner. Having NullRef means that something did not work as it was meant to be - the best practice definitely is to not let that scenario happen.
     
  6. brianasu

    brianasu

    Joined:
    Mar 9, 2010
    Posts:
    369
    Ok thanks for the info. Yeah I know the null ref is really bad but sadly in real life you often release stuff into production and find bugs after. I'm just wondering if the app will work or I have to do a new release immediately.
     
  7. smitchell

    smitchell

    Joined:
    Mar 12, 2012
    Posts:
    702
    well yeah bugs happen; but a null ref isn't bug, it's an error. you could quite easily fix it
     
  8. brianasu

    brianasu

    Joined:
    Mar 9, 2010
    Posts:
    369
    Yup that's true. Anyways thanks for the input.