Help, NullReferenceException: Object reference not set to an instance of an object PlayerAttack.Deal

I get this error on this Line:

void DealDamage()
{
SelectEnemy enemyDeath = GetComponent ();
if (enemyHealth.value <= 0)
enemyDeath.Invoke (“EnemyDeath”, 0f);
else
enemyHealth.value -= playerDamage;
}

the function that i’m trying to invoke (EnemyDeath()) is in another script(SelectEnemy.cs).

Thanks for help.<3

Yo ,

Did you make Enemy death fuction public else it cant connect

and you have to assign the SelectEnemy in your script somting like this

using UnityEngine;
public class ScriptA : MonoBehaviour
{
  public ScriptB other;


  void Update()
  {
    other.DoSomething();
  }
}

and second script

using UnityEngine;
public class ScriptB : MonoBehaviour
{
  public void DoSomething()
  {
     Debug.Log("Hi there");
  }
}

In your case you have to add

public SelectEnemy other;

and

enemyDeath.Invoke (“other.EnemyDeath”, 0f);

Why are you using invoke anyways? You have it set to 0f…

Also, instead of doing it that way, you should have your enemy check if it should die when it takes damage. Your enemy should have a method that takes a parameter for the damage it should take. Let it subtract from it’s health and then check if it should die or not.

2 Likes

To the OP: if you find yourself back on the forums posting in the future, please take a moment to look at this page: Using code tags properly - Unity Engine - Unity Discussions
It shows you how to post code more nicely in the forums. :slight_smile: