Hi,
I wrote two scripts to handle health in my game.
One for my player to have Health and one for enemies to deal damage to my player.
In my DealDamage function it seems that Unity can’t find the playerHealth.currentHealth call. It only gives back a Null Reference Exception Error.
I can not find out what I did wrong.
My PlayerHealth Script:
using UnityEngine;
using System.Collections;
public class PlayerHealth : MonoBehaviour
{
public int startingHealth;
public int currentHealth;
public GameObject playerExplosion;
private GameController gameController;
private bool isDead;
void Start()
{
isDead = false;
GameObject gameControllerObject = GameObject.FindWithTag("GameController");
if (gameControllerObject !=null)
{
gameController = gameControllerObject.GetComponent<GameController>();
}
if(gameController == null)
{
Debug.Log("Cannot find 'GameController' script");
}
}
void Awake()
{
currentHealth = startingHealth;
}
public void TakeDamage(int amount)
{
currentHealth -= amount;
if (currentHealth <= 0 && !isDead)
{
Death ();
}
}
void Death()
{
isDead = true;
Destroy (gameObject);
Instantiate (playerExplosion, transform.position, transform.rotation);
gameController.GameOver();
}
}
and my EnemyHit Script:
using UnityEngine;
using System.Collections;
public class EnemyHit : MonoBehaviour
{
public int attackDamage;
GameObject player;
PlayerHealth playerHealth;
void Start()
{
player = GameObject.FindGameObjectWithTag ("Player");
playerHealth = player.GetComponent<PlayerHealth> ();
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject == player)
{
DealDamage ();
}
}
void DealDamage()
{
if (playerHealth.currentHealth > 0)
{
playerHealth.TakeDamage (attackDamage);
}
}
}