Search Unity

Getting Unity to display variable names for NullRefrenceExceptions

Discussion in 'Scripting' started by SpaceOwlGames, Jan 17, 2022.

  1. SpaceOwlGames

    SpaceOwlGames

    Joined:
    Apr 22, 2016
    Posts:
    61
    Hello,
    We are all familiar with NullRefrenceExceptions and how the error message does not tell you which variable is null in something like: enemy.target.stats.health.shield.curShields as noted in this very old thread:
    https://forum.unity.com/threads/better-nullreferenceexception-error-reporting.12739/

    I came across this: https://stackoverflow.com/questions...how-to-spot-the-culprit-in-the-specified-line - where the answer shows you how to enable settings where Visual Studio 2017+ it does report the null variable name.

    I don't understand if this is applicable at all but it would be GREAT if this somehow could be used in Unity to report back the variable name, it would save us all a huge amount of debugging time whenever this happens.
    Does anyone know if this can be done?

    SIDE QUESTION
    Is there a way to write a function that steps through a chained line of code like this to check which is null?
    Something like this in pseudocode:

    CheckNullHelperFunc(unknowntype codeline){
    foreach(unknowntype.part segment in codeline){
    Debug.Log(segment.name: segment)
    }
    }

    So for null refrence in: enemy.target.stats.health.shield.curShields
    CheckNullHelperFunc(enemy.target.stats.health.shield.curShields);
    Would print out:
    enemy: Object
    target: Object
    stats: NULL
     
  2. RadRedPanda

    RadRedPanda

    Joined:
    May 9, 2018
    Posts:
    1,648
    If you just hook up a debugger to your code you can just look at it line by line and check which variable is null.
    Not only that, you're just giving yourself a headache using a line like
    enemy.target.stats.health.shield.curShields
    , just split it up into different variables and you'll be able to easily see which one is null.
     
    Kurt-Dekker and Joe-Censored like this.
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,752
    Oh my... as Rad Red Panda right points out, if you have more than one or two dots (.) in a single statement, you're just being mean to yourself.

    How to break down hairy lines of code:

    http://plbm.com/?p=248

    Break it up, practice social distancing in your code, one thing per line please.