NullReferenceException: Debugging#

Now we understand reference types and when they are being accessed, we can debug to find which one is null.

Previous knowledge may make this step unnecessary, but if you have multiple access operators on one line, or aren't entirely confident, you need to check by debugging!

Checking with logs#

When logging to find null values it's important to make individual logs for each access, or else the log will also throw an exception and not be printed.

Debug.Log($"Value: {value}");
Debug.Log($"Target: {value.Target}");
Debug.Log($"Image: {value.Target.GetComponent<Image>()}");
Target.GetComponent<Image>().color = Color.white; //<- Line that causes the error

Null values will sometimes print nothing, so note if a log does not print details, it could be a null value.

Learn more.

Checking with the debugger#

Using the debugger is a fast and thorough way of exploring your code's state, where code execution is halted and values can be inspected directly.

Checking for null requires placing a Rider breakpoint breakpoint on that line, and Rider attach attaching the debugger. When the breakpoint is hit you can hover to inspect your variables. Stop the debugger to continue normal execution.

Learn more.

I understand which variable is null.