How to break down “hairy code” that has an error.

Frequently you will encounter an error in a piece of code such as this:

GameObject.FindWithTag("Player").GetComponent<CharacterStats>().AddToStrength(5);  //null ref error here, I needz helpz!!!

With the above code and most IDEs, there is no easy way to reason about what has failed. This means you must rewrite the code to further expose where the error might be.

For instance, the above code could be re-expressed as follows:

// original from above:
//

GameObject.FindWithTag("Player").GetComponent<CharacterStat>().AddToStrength(5); //null ref error here, I needz helpz!!!

// rewrite the above as:
//

GameObject playerObject = GameObject.FindWithTag("Player");
if (playerObject == null)
{
Debug.Log("FindWithTag returned null for Player tag");
}
CharacterStats stats = playerObject.GetComponent<CharacterStats>();
if (stats == null)
{
Debug.Log("playerObject.GetComponent returned null");
}
stats.AddToStrength(5);

Now you can re-run your game and see precisely which statement above is failing, and thus have a chance to fix it.

Hat tip to @Joe-Censored on the Unity3D forums for the above code.

How to fix Index Out Of Range errors in Unity3D

A very common problem in Unity programming is the Index Out Of Bounds Exception

A related cousin is the Argument Out Of Range Exception.

Both mean the same thing. One is for arrays, one is for other types of collections.

What it means is you have a collection of items, but you’re asking for something outside of that collection.

For instance if you have three things, you are asking for the fourth (or greater) one.

Keep in mind that if you have three things, they will be indexed by 0, 1, 2.

If you ask for thing at index 3, that is the fourth thing and it is out of range of a three-thing collection.

Similarly, if you ask for thing -1 (minus one), that also cannot happen.

Another tricky part of this one is that often when you doubleclick on the error, Unity does not take you to the offending line of code, or else it takes you to the wrong line of code.

However, you can still get there manually by looking at the error text itself.

Select the error in the console window and then look down in the lower panel of the console window. Find the first line that is your script, and that will contain a number that tells you where the error is. In some newer versions of Unity you can even click in that window to be taken there.

If after all that you are baffled by why you are getting this error, and you are POSITIVE that there are enough items in your collection to satisfy your dereference operation, then you need to put a Debug.Log() call right before the point where you get the error, and print out two things: the index you are dereferencing, and the Count (or Length) of the collection itself.

Now you have some information to go track down why in fact you do not have enough items in the array.

How to report a problem in the Unity3D forums

Many people struggle with properly reporting a problem on the Unity3D forums. This post is to try and help you get it right and speed up your return to success.

Step 1. Choose a good subject line. Don’t choose “Help!” or “Doesn’t work” Instead say “Need help with inventory system” or “Getting an X error when I pick up an item.”

Step 2. Do a little bit of basic research on your own. Double-click the actual error and try to see what code it relates to. Google the error text itself. Read at least two or three results. You will NEVER be the first person to have this error, trust me.

Step 3. Identify at least the ballpark area where the error is in your code. Extract the relevant section of code, as little as you think will show the problem, and post it here. If you don’t post code, we can’t help you. If you post massive amounts of code, we’ll assume you’re not even trying to be helpful. If nothing is happening, use Debug.Log() to find out if your code is even running.

Step 4. When you post code, use CODE tags (in square brackets) to format your code so we can read it. Do not retype your code; use copy / paste-match-style, otherwise you’ll introduce extra typos.

Step 5. Tell us the following things and be very precise:

1. What you think it should be doing

2. What it actually is doing

3. What things you have tried in order to fix it

4. Any other interesting tidbits you think might be relevant

Keep in mind the point of the Unity forum is not for us to write your script for you. It’s for YOU to write your script, and when you get into trouble, come ask questions in the forums, paying attention to the notes above.

Also if you are following a tutorial, none of us here are going to go and try out the tutorial to see where you have the problem. It falls on you to first understand it well enough to present your issue in terms of the above requirements, otherwise we simply are not going to be able to help you.

How to find a nullref in Unity3D scripting

I am developing a standard “How to handle a nullref” post, since it is the most-common and (usually) simplest form of error encountered when scripting in Unity3D. It is also an error you will see forever into the future as long as you do software engineering. Get really familiar with fixing it.

Steps to find a Null Reference (nullref) error:

In the console, doubleclick the error to figure out where it is in your code.

What is in that line of code that could be null? (reference types obviously)

Is it a complicated hairy line of code? Then break it down into constituent statements, run it again, find where the error is now.

See http://plbm.com/?p=248 for tips on breaking down hairy code.

When you know which variable is null, now ask yourself:

  • what mechanism is supposed to set that variable up? (UnityEditor? GetComponent? GameObject.Find()? Something else?)
  • why is it not being set up? (Unable to find? Misconfigured? Code not being called? Setup code called later than access code? Something else?)
  • fix it.

You can do this. Trust me.

ALSO: often the very first nullref begets 999+ more. ALWAYS start with the very first one at the very top of your log, because often it will trigger all the others, which aren’t really an actual problem.