NullReferenceException: Object reference not set to an instance of an object
I have come across a lot of people that have had this error, however I haven't been able to fix the error myself. I am simply trying to have an enemy collider deal damage to my player.
Player:
public class PlayerHealth : MonoBehaviour {
public int maxHealth = 100;
private int currentHealth;
void Awake()
{
currentHealth = maxHealth;
}
void Start ()
{
print (currentHealth);
}
void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.tag == "Enemy")
{
currentHealth -= GetComponent<EnemyStats> ().enemyDamage;
//currentHealth -= GetComponent<EnemyStats> ().enemyDamage;
Debug.Log("You have been hit!" + currentHealth);
}
}
}
And for the enemy:
public class EnemyStats : MonoBehaviour {
public int maxHealth = 100;
private int currentHealth;
public int enemyDamage = 10;
public int armorRating = 10;
void Awake()
{
currentHealth = maxHealth;
}
public void Damage(int gunDamageAmount)
{
currentHealth -= gunDamageAmount - armorRating;
if (currentHealth <= 0f)
{
gameObject.SetActive (false);
Debug.Log ("Enemy killed!");
}
}
}
Answer by jdean300 · May 02, 2017 at 09:55 PM
The fix is always the same - when Unity pops up the error, double click on it and it will take you to the line of the error. One of the objects in that line is unitialized (null). Method calls such as GetComponent<EnemyStats>()
return null when they do not find a component of the given type. You are calling GetComponent<EnemyStats>()
on the gameObject that has the Player script. You probably want to get it from the enemy, which I am going to assume is the object you expect to be colliding with inside of OnCollisionEnter
.
currentHealth -= collision.gameObject.GetComponent<EnemyStats>().enemyDamage;