1

I am building a 2d Unity game and I am trying to deal damage to an enemy NPC. However, I am having trouble referencing the enemy script to the player script

Getting the following error:

Object reference not set to an instance of an object PlayerAttack.Update ()

Code:

//Creates invisible circle where the player can damage enemy 
// whatIsEnemies is set to a layermask
Collider2D[] enemiesToDamage = Physics2D.OverlapCircleAll(attackPos.position, attackRange, whatIsEnemies);
for(int i = 0; i < enemiesToDamage.Length; i++){
    enemiesToDamage[i].GetComponent<enemy>().TakeDamage(damage); //this line gives error 
}

What am I doing wrong here?

halfer
  • 19,824
  • 17
  • 99
  • 186
  • 2
    Looks like the `.GetComponent()` call might be failing. Hard to tell without the complete exception message. Either that or something else is getting picked up in the whatIsEnemies layer. Not enough information to be able to help here. –  Jan 07 '20 at 19:28
  • Put a `try catch` block and print the content of enemiesToDamage. It seems that one of them doesn't have the script attached (as the `GetComponent` seems the only thing that might fail) – Alvin Sartor Jan 07 '20 at 19:31
  • 2
    It almost certainly means the circle overlaps things like a wall, or other items like lights, floor, anything.. – BugFinder Jan 07 '20 at 19:44
  • just ad a check for null like "if(enemiesToDamage[i].GetComponent() != null)" – Jonathan Alfaro Jan 07 '20 at 19:45
  • adding the check for null will exclude any colliders that do not belong to the enemy – Jonathan Alfaro Jan 07 '20 at 19:45
  • 1
    @Darkonekt Thanks you alot it worked :D! – Samuël W.R Jan 07 '20 at 19:52
  • 1
    @Darkonekt this works as a quick fix but it would probably be better to figure out why stuff is being picked up that doesn't fit the criteria. –  Jan 07 '20 at 20:09
  • Are you sure your whatisEnemies is set properly?? how have you set it? it maybe you have an item miss tagged, or missing the enemy component.. or the mask is wrong – BugFinder Jan 07 '20 at 20:28

1 Answers1

0

Since you are using OverlapCircleAll rather than Collision Matrix you are picking up all kinds of other "collisions".

So one thing you can do is add a null check to exclude all the "non enemy" objects like this:

if(enemiesToDamage[i].GetComponent<enemy>() != null)

Also as Josh points out depending on the situation you might want to figure out why there are "false collisions" being detected in the first place.

Jonathan Alfaro
  • 4,013
  • 3
  • 29
  • 32