Stuck with an error

I was trying to allow player and enemy collide and this error appeared from nowhere.

Its "NullReferenceException: Object reference not set to an instance of an object
Enemy.ProcessHit (DamageDealer damageDealer) (at Assets/Scripts/Enemy.cs:61)
Enemy.OnTriggerEnter2D (UnityEngine.Collider2D collision) (at Assets/Scripts/Enemy.cs:56)"

I am stuck with an issue.

According to me, when player collides with the enemy it triggers the collider 2d to start the destruction of both enemy and player. They both have colliders and they are calling the Hit() method from DamageDealer script.

I am attaching the scripts snaps of enemy as error goes in line 56, 61.

Hi,

Does the other colliding game object have got a DamageDealer attached to its Inspector?

Hello mam, since the other colliding game object is Player but no, I haven’t attached DamageDealer to it.
Is it required to connect it to both the player and enemy.

Your code is looking for a DamageDealer on the other game object. And then it tries to do something with it. Since it didn’t find any, you get a NullReferenceException because your code tries to access a non-existent DamageDealer object.

I directly attached the script to player but still its showing the same error.

Please note, it’s better to copy/paste your code and apply the code fencing characters, rather than using screenshots. Screenshots are ideal for displaying specific details from within a game engine editor or even error messages, but for code, they tend to be less readable, especially on mobile devices which can require extensive zooming and scrolling.

You also prevent those that may offer to help you the ability to copy/paste part of your code back to you with suggestions and/or corrections, meaning that they would need to type a potentially lengthy response. You will often find that people are more likely to respond to your questions if you make it as easy as possible for them to do so.

Maybe the enemy is colliding with something else. I would log other.gameObject.name into the console in the OnTriggerEnter2D method. The enemy needs a DamageDealer as well.


See also;

1 Like

Thanks for showing the right way of asking. That would definitely help in future a lot.

I tried "Debug.Log(gameObject.name) --> (Enemyclone) "
But i found out that enemy is colliding with the TopShredder wall as i placed it near the near game boundary and my enemy path was passing through that wall. :sweat_smile:
And I moved it above and this solved the problem.
@Nina Mam you are awesome :relieved:. Thanks alot

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms