Hi guys, I am a new to the unity. I met a problem when I was dealing with Phrase 6 “Player Health” in a tutorial pack named nightmare in the asset store.
When the Zombunny hit the player, the health of the player doesn’t decrease.
The error said
NullReferenceException: Object reference not set to an instance of an object
CompleteProject.EnemyAttack.Update () (at Assets/_CompletedAssets/Scripts/Enemy/EnemyAttack.cs:58)
I have checked everything but could not find out why. I already attached the PlayerHealth script to the player.
Related links:
using UnityEngine;
using System.Collections;
public class EnemyAttack : MonoBehaviour
{
public float timeBetweenAttacks = 0.5f;
public int attackDamage = 10;
Animator anim;
GameObject player;
PlayerHealth playerHealth;
//EnemyHealth enemyHealth;
bool playerInRange;
float timer;
void Awake ()
{
player = GameObject.FindGameObjectWithTag ("Player");
playerHealth = player.GetComponent <PlayerHealth> ();
//enemyHealth = GetComponent<EnemyHealth>();
anim = GetComponent <Animator> ();
}
void OnTriggerEnter (Collider other)
{
if(other.gameObject == player)
{
playerInRange = true;
}
}
void OnTriggerExit (Collider other)
{
if(other.gameObject == player)
{
playerInRange = false;
}
}
void Update ()
{
timer += Time.deltaTime;
if(timer >= timeBetweenAttacks && playerInRange/* && enemyHealth.currentHealth > 0*/)
{
Attack ();
}
if(playerHealth.currentHealth <= 0)
{
anim.SetTrigger ("PlayerDead");
}
}
void Attack ()
{
timer = 0f;
if(playerHealth.currentHealth > 0)
{
playerHealth.TakeDamage (attackDamage);
}
}
}
