best debugging approach when you're a beginner

Hello guys, I’ve just started to develop in Unity/C# . I 'm experienced in coding ( java and python) but not in C# and neither in Unity. To gets my hands on Unity, I have followed this great tutorial for re-developping flappy bird.

I was half way when I got stuck by a null reference:

console said:

NullReferenceException: Object reference not set to an instance of an object
TapController.OnTriggerEnter2D (UnityEngine.Collider2D col) (at Assets/scripts/TapController.cs:73)

when the bird hit the ground, the code didn’t end well.

the lines are here:

void  OnTriggerEnter2D(Collider2D col){
    if(col.gameObject.tag=="ScoreZone"){
        //register a score amount
        print("OnGameOverConfirmed");  
        OnPlayerScored(); //event sent to GameManager;
        //play a sound
    }

    if (col.gameObject.tag=="DeadZone"){
        rigidbody.simulated=false;
        Debug.Log("DeadZone");
        //register a dead event
        OnPlayerDied(); //event sent to GameManager; NULL HERE !!!
        //play a sound
    }
}

I’m a noob in unity and C# so I spent several hours finding the problem…

It turns out it was just an extremely dumb miswriting in
GameManager.cs

void onEnable(){
    Debug.Log("OnEnable GameManager");
    CountdownText.OnCountdownFinished+=OnCountdownFinished;  
    TapController.OnPlayerDied+=OnPlayerDied;
    TapController.OnPlayerScored+=OnPlayerScored;
}

correct spelling was “OnEnable()”

and same in TapController.

I was trying to install debugger in C# would that have helped me? or not at all?

How can i find such mistakes when the console points on a totally ( to me) unrelated problem?

Do you have any advices?

Thanks for your help

Maybe use an IDE that has Unity magic message auto complete if you’re unfamiliar with it ?

For example when i type “void On” in visual studio it shows this and i can just press enter to have it written entirely.
6996908--826607--upload_2021-4-1_14-48-58.png

If you’re unsure if your method is getting called just log something with Debug.Log(“blabla”), you can also add a break point using the debugger, either way you’ll get as much things happening as it gets when your method is never called…

Dont worry tho now you had the issue it wont happen again :stuck_out_tongue: you’ll get through it.

1 Like

Also want to mention that Visual Studio colors Unity callbacks like OnEnable, Update, Start, etc. differently than regular methods.

By default, regular methods are colored white-ish, while Unity callbacks are colored blue-ish.

So first and foremost, NullReferenceExceptions are rather common and easy to fix. The compiler tells you the specific line where the error occurs in the error message. Go to that line, and see what could be null there. Null basically just means that some object (reference) was not set and is thus “empty”, but you still try to access some of its objects’ contents. If the line containing the exception is complicated and you dont know what part of it is null, split it into more lines until you know exactly what is null. Then think about why it is null, then fix that. Usually you just forgot to fill a variable with content through the inspector, or something along those lines.

In General, for debugging i dont use a debugger. It can help. But you can usually solve the problem rather quickly without one as well. Whats important is to gain new information about the problem!
What we call bugs are usually the differences between specification (what we want) and implementation (what we did). So in the end you want to figure out what this difference is and where it comes from. A common example would be a bool being false, when you expect it to be true (or vice versa), or an integer / float containing a different value from what you think it should have at some point in your code. The approach to solving this can be summarized as:
Find what is different from how you expect it to be, figure out why it is different and then fix it.
To find out what is different, you can now either use a debugger, or put some Debug.Log() statements into your code. Debug.Log() lets you print the messages, including variable values, to the console while your program runs. Using this you can usually quickly determine what is different from how you expect it. After you figured that out, you need to think about why it is different. This can either be obvious, or require you to print some more values using Debug.Log(), until you find the actual problem causing the difference (for example when the value thats wrong is the result of a lengthly calculation, you want to figure out where it starts to differ from your expectations).
After you figured out why something is wrong, change it to work as intended, ie fix the problem.

Hope this helps give you a general overview for how to approach problems :slight_smile:

2 Likes

Thanks a lot guys for all your comments. :wink:

Welcome! I do… Debug.Log() is your friend… as you noted above, a simple misspelling (such as onEnable() will simply result in your code not running, and you gotta find out it’s not running. Fixing broken code that doesn’t run isn’t going to change anything, obviously! Same goes for putting your script on the wrong GameObject, not putting it on at all, having the GameObject inactive, etc.

Alternately, fire up the debugger and attach and set some breakpoints. But depending on the code and problem, this can make an interactive game problem VERY tricky, since when a breakpoint hits, Unity actually freezes, and then all your buttons and/or joystick inputs revert to OFF, and Unity might not catch that, leaving you stuck moving.

Here’s my standard blurb for debugging in Unity:

To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

Doing this should help you answer these types of questions:

  • is this code even running? which parts are running? how often does it run?
  • what are the values of the variables involved? Are they initialized?

Knowing this information will help you reason about the behavior you are seeing.

And @Yoreki above pretty much gave you the full Null reference trackdown steps, but I’ll include my copy anyway:

The answer is always the same… ALWAYS. It is the single most common error ever.

Don’t waste your life spinning around and round on this error. Instead, learn how to fix it fast… it’s EASY!!

Some notes on how to fix a NullReferenceException error in Unity3D

  • also known as: Unassigned Reference Exception
  • also known as: Missing Reference Exception
  • also known as: Object reference not set to an instance of an object

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

The basic steps outlined above are:

  • Identify what is null
  • Identify why it is null
  • Fix that.

Expect to see this error a LOT. It’s easily the most common thing to do when working. Learn how to fix it rapidly. It’s easy. See the above link for more tips.

This is the kind of mindset and thinking process you need to bring to this problem:

https://discussions.unity.com/t/814091/4

Step by step, break it down, find the problem.

There is a PlugIn for Visual Studio to debug the code, if your game runs in Unity. It can be installed via the Visual Studio Launcher/Installer

If i remember correctly it´s the one you see here on min 1:32:

I personally prefer the Debugger of Visual Studio, because you can go steps back in the process. For example: You have an object which is null (as in your case) and you use the object in several places, you can easy go back to the other methods that are called before and check on which part the object maybe wasn´t null yet, without putting a Debug.Log() on each method which was called before. Another example which i had yesterday: i created a new object and set some values. As i loaded it, the values were overwritten. With the debugger i checked if values are alright wrong if the object was stored, or if it happened on the loading part and i could see, that on the save was all fine. So i new it happens on loading.

I think in some cases it makes more sense to have the Debugger and in other just put some logs. But at the end it´s up to you, which way you prefer :slight_smile: