NullReferenceException by detecting health
Hello everyone, I'm working on a fps zombie game, currently I'm writing the code for the AI of the zombies.
My AI use a detection for don't attacking a player already dead, for detect this I use this line of code :
if (CurrentHealth > 0 && PlayerHealth.CurrentHealth > 0)
{
anim.SetBool ("IsIdle", false);
nav.SetDestination (player.position);
nav.speed = ZombieSpeed;
}
"CurrentHealth" is the current health of my zombie and "PlayerHealth.CurrentHealth" is the current health of the player.
So i want to detect if my zombie and my player have more than 0 health point to trigger the attack. Unity give me this error : "NullReferenceException: Object reference not set to an instance of an object" The problem seems to coming from the "if(......)", but I don't know what I'm doing wrong, all works perfectly except this.
So this piece of code is not correct ? Where is my mistake(s) ? I looked at different websites/forum, but I've don't found a solution.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ZombieAI : $$anonymous$$onoBehaviour
{
public float ZombieSpeed = 3f;
public float TimeBetwheenAttacks = 0.5f;
public int AttackDamage = 10;
public int StartingHealth = 50;
public int CurrentHealth;
private Transform player;
private Animator anim;
private UnityEngine.AI.Nav$$anonymous$$eshAgent nav;
private PlayerHealth playerHealth;
private bool PlayerInRange;
private bool IsDead;
void Awake ()
{
player = GameObject.FindGameObjectWithTag ("Player").transform;
nav = GetComponent<UnityEngine.AI.Nav$$anonymous$$eshAgent> ();
playerHealth = player.GetComponent<PlayerHealth> ();
CurrentHealth = StartingHealth;
PlayerInRange = false;
IsDead = false;
}
void Update ()
{
if (CurrentHealth > 0 && PlayerHealth.CurrentHealth > 0)
{
anim.SetBool ("IsIdle", false);
nav.SetDestination (player.position);
nav.speed = ZombieSpeed;
}
}
}
Answer by vir1234 · Jul 28, 2017 at 11:29 AM
first you havent set reference anim in the script. is your CurrentHealth is static?
I didn't see, I fixed this but I have still the same problem
use if (CurrentHealth > 0 && playerHealth.CurrentHealth > 0) and are you sure is there Player tag on the object ?
$$anonymous$$y bad, I launched again the game and the error just disappear. I feel stupid ... I can't believe it's don't work because of the animator !
Thanks you for your help, now I can keep working on my game
Your answer
Follow this Question
Related Questions
How to create a semi-intelligent trigger system? 0 Answers
Sin function returns NaN 1 Answer
Unity ads initialize error 1 Answer
How can I remove the red error text from Pixel Perfect Camera? 0 Answers