NullReferenceException: Object reference not set to an instance of an object Player.

NullReferenceException: Object reference not set to an instance of an object
Player.OnTriggerEnter2D (UnityEngine.Collider2D collision) (at Assets/Scripts/Player.cs:34)

This is the error i’m getting in unity.

Here are some screenshots.
1.

There is contact between the 2. as you can see by the Debug.Log().
but then i get the error.

Thanks in advance!

You never need to post for NullReference because 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
  • Identify why it is null
  • Fix that

ALSO, for future posting, photographs of code ARE NOT A THING.

If you post a code snippet, ALWAYS USE CODE TAGS:

How to use code tags: https://discussions.unity.com/t/481379

Be sure the script name is correct (“Enemy”)

I can’t recall exactly, but you may need to get the parent before using GetComponent here (?) so it would be
collision.gameObject.GetComponent().Damage();

Also, this is optional, but I wouldn’t name it “collision”. There is a Collision object used in OnCollisionEnter2D which returns different information than the OnTriggerEnter2D method does. Can be confusing. Usually with a Trigger the variable name is collider, because that’s what it returns.

The error occurs because you are pointing towards something that is null. Which means your line 34, collision.GetComponent().Damage() is null.

Your enemy probably doesn’t have an Enemy script attached to it. Thus GetComponent() will return null.

You may have already resolved this issue, but here’s a video on the error if it helps: