I am getting an error about an object reference not set to an instance of that object.

The error is: “Object reference not set to an instance of an object Projectile.OnTriggerEnter (UnityEngine.Collider other) (at Assets/Scripts/Items/Projectile.cs:43).”

Here is my code where the error occurs, please help:
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag(“Enemy”) && other != null)
{
other.GetComponent().takeDamage(20f);
}
}

The answer is always the same… ALWAYS!

How to fix a NullReferenceException error

https://forum.unity.com/threads/how-to-fix-a-nullreferenceexception-error.1230297/

Three steps to success:

  • Identify what is null ← any other action taken before this step is WASTED TIME
  • Identify why it is null
  • Fix that

I understand but I added the conditional to check if the collider is not null. I can’t think of what else would be null, I am new to Unity and C# so could it be that a tag is null, or perhaps gameObject.

Then that’s not what is null. You haven’t completed step #1.

Pretty sure other would never be null either, and remember, logic is evaluated left to right.

You have hairy lines of code that get and use stuff blindly. Don’t do that. It’s almost certainly the source of your crash.

You’ll see what is actually null when you pull the code apart properly as below:

EDIT: Take a moment also and ask why you are checking if something is tagged as an enemy, then getting the Player Component off of it. Something doesn’t add up.

If you have more than one or two dots (.) in a single statement, you’re just being mean to yourself.

Putting it all one one line DOES NOT make it faster. That’s not how compiled code works.

How to break down hairy lines of code:

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

Break it up, practice social distancing in your code, one thing per line please.

“Programming is hard enough without making it harder for ourselves.” - angrypenguin on Unity3D forums

“Combining a bunch of stuff into one line always feels satisfying, but it’s always a PITA to debug.” - StarManta on the Unity3D forums

That makes sense because I was trying to access a script that wasn’t even a component of the the enemy game object.

Kurt I love you.