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.

0 Shares

Leave a Reply

Your email address will not be published. Required fields are marked *