Yet another Object reference not set to an instance of an object

(I wouldn’t be surprised if this was the most common error Unity spits out at you when dealing with multiple scripts.)

Whenever I try to reference the currentHealth from my PlayerHealth script, I get the too common “Object reference not set to an instance of an object” error. Here are the two scripts that I’m using where I’m getting this error:

PlayerHealth:

PawnshipAttack:

Here’s the full error:
NullReferenceException: Object reference not set to an instance of an object
PawnshipAttack.Attack () (at Assets/Scripts/PawnshipAttack.cs:46)

If anyone could help me with this, that’d be amazing.

Please insert your code in your post using code tags (see the proper button in the post toolbar).

Null reference absolutely is the most common error you’re likely to see. You should get used to solving these yourself because you’ll see them all the time. :slight_smile:

The error message gives you the exact line number where the problem occurs, so it should be easy to figure out which object is null. Then you just have to figure out why.

Null reference errors are always resolved the same way. Doesn’t matter your code, doesn’t matter your situation, doesn’t matter anything.

  1. Go to the specific line of code the null reference occurs and figure out which references are being accessed
  2. If more than one references are used in step 1, add debugging prior to the line to determine which reference is null, and/or break up the line into separates lines for the same purpose
  3. Now that you know which reference is null, make it not null before using it or don’t use it when it is expected to be null

I’d beg to differ, haha. @lordofduct

https://discussions.unity.com/t/696234

2 Likes