Hello. So I’m working on my first game (still pretty new to C# scripting). I’ve gotten a damage system working when my player comes into contact with an enemy; now I’m trying to get a damage system working to where my player can damage the enemy back, but I’m running into this NullReferenceException.
This is my DamageDealer script which subtracts health from my player (and hopefully eventually my enemy too)
using UnityEngine;
using System.Collections;
public class DamageDealer : MonoBehaviour
{
public float health;//Players health
public GameObject ragdoll;
public void TakeDamage(float dmg)
{
health = health - dmg;
if (health <= 0)
{
Debug.Log(“Die”);//Print out Die to console for troubleshooting
}
}
}
And this is the part of my EnemyController script (which extends DamageDealer) and deals with the collision detection:
void OnTriggerEnter(Collider c)
{
//If player is hit by enemy, deal damage to player
if (c.tag == “Player”) {//If enemy contacts player
canAttackPlayer = true;
animator.SetBool (“Can Attack Player”, true);//Attack by changing canAttackPlayer bool in Animator
//Debug.Log (“Player is hit”);
c.GetComponent ().TakeDamage (10);//Deals 10 damage (Calls TakeDamage method from DamageDealer class)
}
//If enemy is hit by spell, deal damage to enemy
if (c.tag == “Spell”) { //If spell contacts enemy
Debug.Log (“Enemy is hit”);
c.GetComponent ().TakeDamage (10);//Deals 10 damage (Calls TakeDamage method from DamageDealer class)
}
}
The NullReferenceException is occurring when I try to call
c.GetComponent ().TakeDamage (10);
after checking if c.tag == “Spell”.
The exact error message is: “NullReferenceException: Object reference not set to an instance of an object”
Any pointers in the right direction are appreciated!