- Home /
Question by
Shindy117 · Jun 18, 2017 at 04:23 PM ·
gameobjectplayerdestroynullreferenceexceptionfalse
Instance of a object error after player death
Hello all
so I am getting a instance of a object error whenever my player gets destroyed. Now when he gets destroyed I set the gameobject to "false". Then my enemy attack script gets a error on the:
playerHealth = player.GetComponent<PlayerHealth>();
line of code. I know why this is happening but I don't understand how to fix it. Any examples of ways to destroy players and still have scripts access them their components for damage?
Here is my entire script: public class EnemyAttack : MonoBehaviour {
public int meleeAttackDamage; //leave empty we will set this value in inspector for each certain enemy
public float timeBetweenAttacks = 0.5f;
public GameObject fireBall;
public Transform spider;
public float fireDelay;
private float timer;
private GameObject player;
private PlayerHealth playerHealth;
private EnemyHealth enemyHealth;
private bool playerInRange;
void Awake()
{
player = GameObject.FindGameObjectWithTag("Player");
playerHealth = player.GetComponent<PlayerHealth>();
enemyHealth = GetComponentInParent<EnemyHealth>();
fireDelay = 5f;
}
void Update()
{
timer += Time.deltaTime;
fireDelay -= Time.deltaTime;
FireShot();
if(timer >= timeBetweenAttacks && playerInRange && enemyHealth.currentHealth > 0)
{
MeleeAttack();
}
}
void FireShot()
{
if (fireBall != null)
{
//Add current enemy projectile code here.
if (fireDelay <= 0)
{
Instantiate(fireBall, spider.position, spider.rotation);
fireDelay = 5f;
}
}
}
//This is melee attack
void MeleeAttack()
{
timer = 0f;
if (playerHealth.currentHealth > 0 && playerHealth.playerShield == 0)
{
playerHealth.TakeDamage(meleeAttackDamage);
if (playerHealth.currentHealth <= 0)
{
playerInRange = false;
}
}
else if (playerHealth.playerShield > 0)
{
playerHealth.playerShield -= meleeAttackDamage;
}
}
void OnTriggerEnter(Collider entity)
{
if(entity.gameObject == player)
{
playerInRange = true;
}
}
void OnTriggerExit(Collider entity)
{
if(entity.gameObject == player)
{
playerInRange = false;
}
}
}
Comment
$$anonymous$$ake your character SetActive(false) ins$$anonymous$$d of destroying.